home *** CD-ROM | disk | FTP | other *** search
/ Games of Daze / Infomagic - Games of Daze (Summer 1995) (Disc 1 of 2).iso / djgpp / docs / gcc / extend.tex < prev    next >
Encoding:
Text File  |  1994-12-21  |  108.0 KB  |  2,920 lines

  1. @c Copyright (C) 1988, 1989, 1992, 1993, 1994 Free Software Foundation, Inc.
  2. @c This is part of the GCC manual.
  3. @c For copying conditions, see the file gcc.texi.
  4.  
  5. @node C Extensions
  6. @chapter Extensions to the C Language Family
  7. @cindex extensions, C language
  8. @cindex C language extensions
  9.  
  10. GNU C provides several language features not found in ANSI standard C.
  11. (The @samp{-pedantic} option directs GNU CC to print a warning message if
  12. any of these features is used.)  To test for the availability of these
  13. features in conditional compilation, check for a predefined macro
  14. @code{__GNUC__}, which is always defined under GNU CC.
  15.  
  16. These extensions are available in C and Objective C.  Most of them are
  17. also available in C++.  @xref{C++ Extensions,,Extensions to the
  18. C++ Language}, for extensions that apply @emph{only} to C++.
  19.  
  20. @c The only difference between the two versions of this menu is that the
  21. @c version for clear INTERNALS has an extra node, "Constraints" (which
  22. @c appears in a separate chapter in the other version of the manual).
  23. @ifset INTERNALS
  24. @menu
  25. * Statement Exprs::     Putting statements and declarations inside expressions.
  26. * Local Labels::        Labels local to a statement-expression.
  27. * Labels as Values::    Getting pointers to labels, and computed gotos.
  28. * Nested Functions::    As in Algol and Pascal, lexical scoping of functions.
  29. * Constructing Calls::    Dispatching a call to another function.
  30. * Naming Types::        Giving a name to the type of some expression.
  31. * Typeof::              @code{typeof}: referring to the type of an expression.
  32. * Lvalues::             Using @samp{?:}, @samp{,} and casts in lvalues.
  33. * Conditionals::        Omitting the middle operand of a @samp{?:} expression.
  34. * Long Long::        Double-word integers---@code{long long int}.
  35. * Complex::             Data types for complex numbers.
  36. * Zero Length::         Zero-length arrays.
  37. * Variable Length::     Arrays whose length is computed at run time.
  38. * Macro Varargs::    Macros with variable number of arguments.
  39. * Subscripting::        Any array can be subscripted, even if not an lvalue.
  40. * Pointer Arith::       Arithmetic on @code{void}-pointers and function pointers.
  41. * Initializers::        Non-constant initializers.
  42. * Constructors::        Constructor expressions give structures, unions
  43.                          or arrays as values.
  44. * Labeled Elements::    Labeling elements of initializers.
  45. * Cast to Union::       Casting to union type from any member of the union.
  46. * Case Ranges::        `case 1 ... 9' and such.
  47. * Function Attributes:: Declaring that functions have no side effects,
  48.                          or that they can never return.
  49. * Function Prototypes:: Prototype declarations and old-style definitions.
  50. * Dollar Signs::        Dollar sign is allowed in identifiers.
  51. * Character Escapes::   @samp{\e} stands for the character @key{ESC}.
  52. * Variable Attributes::    Specifying attributes of variables.
  53. * Alignment::           Inquiring about the alignment of a type or variable.
  54. * Inline::              Defining inline functions (as fast as macros).
  55. * Extended Asm::        Assembler instructions with C expressions as operands.
  56.                          (With them you can define ``built-in'' functions.)
  57. * Asm Labels::          Specifying the assembler name to use for a C symbol.
  58. * Explicit Reg Vars::   Defining variables residing in specified registers.
  59. * Alternate Keywords::  @code{__const__}, @code{__asm__}, etc., for header files.
  60. * Incomplete Enums::    @code{enum foo;}, with details to follow.
  61. * Function Names::    Printable strings which are the name of the current
  62.              function.
  63. @end menu
  64. @end ifset
  65. @ifclear INTERNALS
  66. @menu
  67. * Statement Exprs::     Putting statements and declarations inside expressions.
  68. * Local Labels::        Labels local to a statement-expression.
  69. * Labels as Values::    Getting pointers to labels, and computed gotos.
  70. * Nested Functions::    As in Algol and Pascal, lexical scoping of functions.
  71. * Constructing Calls::    Dispatching a call to another function.
  72. * Naming Types::        Giving a name to the type of some expression.
  73. * Typeof::              @code{typeof}: referring to the type of an expression.
  74. * Lvalues::             Using @samp{?:}, @samp{,} and casts in lvalues.
  75. * Conditionals::        Omitting the middle operand of a @samp{?:} expression.
  76. * Long Long::        Double-word integers---@code{long long int}.
  77. * Complex::             Data types for complex numbers.
  78. * Zero Length::         Zero-length arrays.
  79. * Variable Length::     Arrays whose length is computed at run time.
  80. * Macro Varargs::    Macros with variable number of arguments.
  81. * Subscripting::        Any array can be subscripted, even if not an lvalue.
  82. * Pointer Arith::       Arithmetic on @code{void}-pointers and function pointers.
  83. * Initializers::        Non-constant initializers.
  84. * Constructors::        Constructor expressions give structures, unions
  85.                          or arrays as values.
  86. * Labeled Elements::    Labeling elements of initializers.
  87. * Cast to Union::       Casting to union type from any member of the union.
  88. * Case Ranges::        `case 1 ... 9' and such.
  89. * Function Attributes:: Declaring that functions have no side effects,
  90.                          or that they can never return.
  91. * Function Prototypes:: Prototype declarations and old-style definitions.
  92. * Dollar Signs::        Dollar sign is allowed in identifiers.
  93. * Character Escapes::   @samp{\e} stands for the character @key{ESC}.
  94. * Variable Attributes::    Specifying attributes of variables.
  95. * Alignment::           Inquiring about the alignment of a type or variable.
  96. * Inline::              Defining inline functions (as fast as macros).
  97. * Extended Asm::        Assembler instructions with C expressions as operands.
  98.                          (With them you can define ``built-in'' functions.)
  99. * Constraints::         Constraints for asm operands
  100. * Asm Labels::          Specifying the assembler name to use for a C symbol.
  101. * Explicit Reg Vars::   Defining variables residing in specified registers.
  102. * Alternate Keywords::  @code{__const__}, @code{__asm__}, etc., for header files.
  103. * Incomplete Enums::    @code{enum foo;}, with details to follow.
  104. * Function Names::    Printable strings which are the name of the current
  105.              function.
  106. @end menu
  107. @end ifclear
  108.  
  109. @node Statement Exprs
  110. @section Statements and Declarations in Expressions
  111. @cindex statements inside expressions
  112. @cindex declarations inside expressions
  113. @cindex expressions containing statements
  114. @cindex macros, statements in expressions
  115.  
  116. @c the above section title wrapped and causes an underfull hbox.. i
  117. @c changed it from "within" to "in". --mew 4feb93
  118.  
  119. A compound statement enclosed in parentheses may appear as an expression
  120. in GNU C.  This allows you to use loops, switches, and local variables
  121. within an expression.
  122.  
  123. Recall that a compound statement is a sequence of statements surrounded
  124. by braces; in this construct, parentheses go around the braces.  For
  125. example:
  126.  
  127. @example
  128. (@{ int y = foo (); int z;
  129.    if (y > 0) z = y;
  130.    else z = - y;
  131.    z; @})
  132. @end example
  133.  
  134. @noindent
  135. is a valid (though slightly more complex than necessary) expression
  136. for the absolute value of @code{foo ()}.
  137.  
  138. The last thing in the compound statement should be an expression
  139. followed by a semicolon; the value of this subexpression serves as the
  140. value of the entire construct.  (If you use some other kind of statement
  141. last within the braces, the construct has type @code{void}, and thus
  142. effectively no value.)
  143.  
  144. This feature is especially useful in making macro definitions ``safe'' (so
  145. that they evaluate each operand exactly once).  For example, the
  146. ``maximum'' function is commonly defined as a macro in standard C as
  147. follows:
  148.  
  149. @example
  150. #define max(a,b) ((a) > (b) ? (a) : (b))
  151. @end example
  152.  
  153. @noindent
  154. @cindex side effects, macro argument
  155. But this definition computes either @var{a} or @var{b} twice, with bad
  156. results if the operand has side effects.  In GNU C, if you know the
  157. type of the operands (here let's assume @code{int}), you can define
  158. the macro safely as follows:
  159.  
  160. @example
  161. #define maxint(a,b) \
  162.   (@{int _a = (a), _b = (b); _a > _b ? _a : _b; @})
  163. @end example
  164.  
  165. Embedded statements are not allowed in constant expressions, such as
  166. the value of an enumeration constant, the width of a bit field, or
  167. the initial value of a static variable.
  168.  
  169. If you don't know the type of the operand, you can still do this, but you
  170. must use @code{typeof} (@pxref{Typeof}) or type naming (@pxref{Naming
  171. Types}).
  172.  
  173. @node Local Labels
  174. @section Locally Declared Labels
  175. @cindex local labels
  176. @cindex macros, local labels
  177.  
  178. Each statement expression is a scope in which @dfn{local labels} can be
  179. declared.  A local label is simply an identifier; you can jump to it
  180. with an ordinary @code{goto} statement, but only from within the
  181. statement expression it belongs to.
  182.  
  183. A local label declaration looks like this:
  184.  
  185. @example
  186. __label__ @var{label};
  187. @end example
  188.  
  189. @noindent
  190. or
  191.  
  192. @example
  193. __label__ @var{label1}, @var{label2}, @dots{};
  194. @end example
  195.  
  196. Local label declarations must come at the beginning of the statement
  197. expression, right after the @samp{(@{}, before any ordinary
  198. declarations.
  199.  
  200. The label declaration defines the label @emph{name}, but does not define
  201. the label itself.  You must do this in the usual way, with
  202. @code{@var{label}:}, within the statements of the statement expression.
  203.  
  204. The local label feature is useful because statement expressions are
  205. often used in macros.  If the macro contains nested loops, a @code{goto}
  206. can be useful for breaking out of them.  However, an ordinary label
  207. whose scope is the whole function cannot be used: if the macro can be
  208. expanded several times in one function, the label will be multiply
  209. defined in that function.  A local label avoids this problem.  For
  210. example:
  211.  
  212. @example
  213. #define SEARCH(array, target)                     \
  214. (@{                                               \
  215.   __label__ found;                                \
  216.   typeof (target) _SEARCH_target = (target);      \
  217.   typeof (*(array)) *_SEARCH_array = (array);     \
  218.   int i, j;                                       \
  219.   int value;                                      \
  220.   for (i = 0; i < max; i++)                       \
  221.     for (j = 0; j < max; j++)                     \
  222.       if (_SEARCH_array[i][j] == _SEARCH_target)  \
  223.         @{ value = i; goto found; @}              \
  224.   value = -1;                                     \
  225.  found:                                           \
  226.   value;                                          \
  227. @})
  228. @end example
  229.  
  230. @node Labels as Values
  231. @section Labels as Values
  232. @cindex labels as values
  233. @cindex computed gotos
  234. @cindex goto with computed label 
  235. @cindex address of a label
  236.  
  237. You can get the address of a label defined in the current function
  238. (or a containing function) with the unary operator @samp{&&}.  The
  239. value has type @code{void *}.  This value is a constant and can be used 
  240. wherever a constant of that type is valid.  For example:
  241.  
  242. @example
  243. void *ptr;
  244. @dots{}
  245. ptr = &&foo;
  246. @end example
  247.  
  248. To use these values, you need to be able to jump to one.  This is done
  249. with the computed goto statement@footnote{The analogous feature in
  250. Fortran is called an assigned goto, but that name seems inappropriate in
  251. C, where one can do more than simply store label addresses in label
  252. variables.}, @code{goto *@var{exp};}.  For example,
  253.  
  254. @example
  255. goto *ptr;
  256. @end example
  257.  
  258. @noindent
  259. Any expression of type @code{void *} is allowed.
  260.  
  261. One way of using these constants is in initializing a static array that
  262. will serve as a jump table:
  263.  
  264. @example
  265. static void *array[] = @{ &&foo, &&bar, &&hack @};
  266. @end example
  267.  
  268. Then you can select a label with indexing, like this:
  269.  
  270. @example
  271. goto *array[i];
  272. @end example
  273.  
  274. @noindent
  275. Note that this does not check whether the subscript is in bounds---array
  276. indexing in C never does that.
  277.  
  278. Such an array of label values serves a purpose much like that of the
  279. @code{switch} statement.  The @code{switch} statement is cleaner, so
  280. use that rather than an array unless the problem does not fit a
  281. @code{switch} statement very well.
  282.  
  283. Another use of label values is in an interpreter for threaded code.
  284. The labels within the interpreter function can be stored in the
  285. threaded code for super-fast dispatching.  
  286.  
  287. You can use this mechanism to jump to code in a different function.  If
  288. you do that, totally unpredictable things will happen.  The best way to
  289. avoid this is to store the label address only in automatic variables and
  290. never pass it as an argument.
  291.  
  292. @node Nested Functions
  293. @section Nested Functions
  294. @cindex nested functions
  295. @cindex downward funargs
  296. @cindex thunks
  297.  
  298. A @dfn{nested function} is a function defined inside another function.
  299. (Nested functions are not supported for GNU C++.)  The nested function's
  300. name is local to the block where it is defined.  For example, here we
  301. define a nested function named @code{square}, and call it twice:
  302.  
  303. @example
  304. @group
  305. foo (double a, double b)
  306. @{
  307.   double square (double z) @{ return z * z; @}
  308.  
  309.   return square (a) + square (b);
  310. @}
  311. @end group
  312. @end example
  313.  
  314. The nested function can access all the variables of the containing
  315. function that are visible at the point of its definition.  This is
  316. called @dfn{lexical scoping}.  For example, here we show a nested
  317. function which uses an inherited variable named @code{offset}:
  318.  
  319. @example
  320. bar (int *array, int offset, int size)
  321. @{
  322.   int access (int *array, int index)
  323.     @{ return array[index + offset]; @}
  324.   int i;
  325.   @dots{}
  326.   for (i = 0; i < size; i++)
  327.     @dots{} access (array, i) @dots{}
  328. @}
  329. @end example
  330.  
  331. Nested function definitions are permitted within functions in the places
  332. where variable definitions are allowed; that is, in any block, before
  333. the first statement in the block.
  334.  
  335. It is possible to call the nested function from outside the scope of its
  336. name by storing its address or passing the address to another function:
  337.  
  338. @example
  339. hack (int *array, int size)
  340. @{
  341.   void store (int index, int value)
  342.     @{ array[index] = value; @}
  343.  
  344.   intermediate (store, size);
  345. @}
  346. @end example
  347.  
  348. Here, the function @code{intermediate} receives the address of
  349. @code{store} as an argument.  If @code{intermediate} calls @code{store},
  350. the arguments given to @code{store} are used to store into @code{array}.
  351. But this technique works only so long as the containing function
  352. (@code{hack}, in this example) does not exit.
  353.  
  354. If you try to call the nested function through its address after the
  355. containing function has exited, all hell will break loose.  If you try
  356. to call it after a containing scope level has exited, and if it refers
  357. to some of the variables that are no longer in scope, you may be lucky,
  358. but it's not wise to take the risk.  If, however, the nested function
  359. does not refer to anything that has gone out of scope, you should be
  360. safe.
  361.  
  362. GNU CC implements taking the address of a nested function using a
  363. technique called @dfn{trampolines}.  A paper describing them is
  364. available from @samp{maya.idiap.ch} in directory @file{pub/tmb},
  365. file @file{usenix88-lexic.ps.Z}.
  366.  
  367. A nested function can jump to a label inherited from a containing
  368. function, provided the label was explicitly declared in the containing
  369. function (@pxref{Local Labels}).  Such a jump returns instantly to the
  370. containing function, exiting the nested function which did the
  371. @code{goto} and any intermediate functions as well.  Here is an example:
  372.  
  373. @example
  374. @group
  375. bar (int *array, int offset, int size)
  376. @{
  377.   __label__ failure;
  378.   int access (int *array, int index)
  379.     @{
  380.       if (index > size)
  381.         goto failure;
  382.       return array[index + offset];
  383.     @}
  384.   int i;
  385.   @dots{}
  386.   for (i = 0; i < size; i++)
  387.     @dots{} access (array, i) @dots{}
  388.   @dots{}
  389.   return 0;
  390.  
  391.  /* @r{Control comes here from @code{access}
  392.     if it detects an error.}  */
  393.  failure:
  394.   return -1;
  395. @}
  396. @end group
  397. @end example
  398.  
  399. A nested function always has internal linkage.  Declaring one with
  400. @code{extern} is erroneous.  If you need to declare the nested function
  401. before its definition, use @code{auto} (which is otherwise meaningless
  402. for function declarations).
  403.  
  404. @example
  405. bar (int *array, int offset, int size)
  406. @{
  407.   __label__ failure;
  408.   auto int access (int *, int);
  409.   @dots{}
  410.   int access (int *array, int index)
  411.     @{
  412.       if (index > size)
  413.         goto failure;
  414.       return array[index + offset];
  415.     @}
  416.   @dots{}
  417. @}
  418. @end example
  419.  
  420. @node Constructing Calls
  421. @section Constructing Function Calls
  422. @cindex constructing calls
  423. @cindex forwarding calls
  424.  
  425. Using the built-in functions described below, you can record
  426. the arguments a function received, and call another function
  427. with the same arguments, without knowing the number or types
  428. of the arguments.
  429.  
  430. You can also record the return value of that function call,
  431. and later return that value, without knowing what data type
  432. the function tried to return (as long as your caller expects
  433. that data type).
  434.  
  435. @table @code
  436. @findex __builtin_apply_args
  437. @item __builtin_apply_args ()
  438. This built-in function returns a pointer of type @code{void *} to data
  439. describing how to perform a call with the same arguments as were passed
  440. to the current function.
  441.  
  442. The function saves the arg pointer register, structure value address,
  443. and all registers that might be used to pass arguments to a function
  444. into a block of memory allocated on the stack.  Then it returns the
  445. address of that block.
  446.  
  447. @findex __builtin_apply
  448. @item __builtin_apply (@var{function}, @var{arguments}, @var{size})
  449. This built-in function invokes @var{function} (type @code{void (*)()})
  450. with a copy of the parameters described by @var{arguments} (type
  451. @code{void *}) and @var{size} (type @code{int}).
  452.  
  453. The value of @var{arguments} should be the value returned by
  454. @code{__builtin_apply_args}.  The argument @var{size} specifies the size
  455. of the stack argument data, in bytes.
  456.  
  457. This function returns a pointer of type @code{void *} to data describing
  458. how to return whatever value was returned by @var{function}.  The data
  459. is saved in a block of memory allocated on the stack.
  460.  
  461. It is not always simple to compute the proper value for @var{size}.  The
  462. value is used by @code{__builtin_apply} to compute the amount of data
  463. that should be pushed on the stack and copied from the incoming argument
  464. area.
  465.  
  466. @findex __builtin_return
  467. @item __builtin_return (@var{result})
  468. This built-in function returns the value described by @var{result} from
  469. the containing function.  You should specify, for @var{result}, a value
  470. returned by @code{__builtin_apply}.
  471. @end table
  472.  
  473. @node Naming Types
  474. @section Naming an Expression's Type
  475. @cindex naming types
  476.  
  477. You can give a name to the type of an expression using a @code{typedef}
  478. declaration with an initializer.  Here is how to define @var{name} as a
  479. type name for the type of @var{exp}:
  480.  
  481. @example
  482. typedef @var{name} = @var{exp};
  483. @end example
  484.  
  485. This is useful in conjunction with the statements-within-expressions
  486. feature.  Here is how the two together can be used to define a safe
  487. ``maximum'' macro that operates on any arithmetic type:
  488.  
  489. @example
  490. #define max(a,b) \
  491.   (@{typedef _ta = (a), _tb = (b);  \
  492.     _ta _a = (a); _tb _b = (b);     \
  493.     _a > _b ? _a : _b; @})
  494. @end example
  495.  
  496. @cindex underscores in variables in macros
  497. @cindex @samp{_} in variables in macros
  498. @cindex local variables in macros
  499. @cindex variables, local, in macros
  500. @cindex macros, local variables in
  501.  
  502. The reason for using names that start with underscores for the local
  503. variables is to avoid conflicts with variable names that occur within the
  504. expressions that are substituted for @code{a} and @code{b}.  Eventually we
  505. hope to design a new form of declaration syntax that allows you to declare
  506. variables whose scopes start only after their initializers; this will be a
  507. more reliable way to prevent such conflicts.
  508.  
  509. @node Typeof
  510. @section Referring to a Type with @code{typeof}
  511. @findex typeof
  512. @findex sizeof
  513. @cindex macros, types of arguments
  514.  
  515. Another way to refer to the type of an expression is with @code{typeof}.
  516. The syntax of using of this keyword looks like @code{sizeof}, but the
  517. construct acts semantically like a type name defined with @code{typedef}.
  518.  
  519. There are two ways of writing the argument to @code{typeof}: with an
  520. expression or with a type.  Here is an example with an expression:
  521.  
  522. @example
  523. typeof (x[0](1))
  524. @end example
  525.  
  526. @noindent
  527. This assumes that @code{x} is an array of functions; the type described
  528. is that of the values of the functions.
  529.  
  530. Here is an example with a typename as the argument:
  531.  
  532. @example
  533. typeof (int *)
  534. @end example
  535.  
  536. @noindent
  537. Here the type described is that of pointers to @code{int}.
  538.  
  539. If you are writing a header file that must work when included in ANSI C
  540. programs, write @code{__typeof__} instead of @code{typeof}.
  541. @xref{Alternate Keywords}.
  542.  
  543. A @code{typeof}-construct can be used anywhere a typedef name could be
  544. used.  For example, you can use it in a declaration, in a cast, or inside
  545. of @code{sizeof} or @code{typeof}.
  546.  
  547. @itemize @bullet
  548. @item
  549. This declares @code{y} with the type of what @code{x} points to.
  550.  
  551. @example
  552. typeof (*x) y;
  553. @end example
  554.  
  555. @item
  556. This declares @code{y} as an array of such values.
  557.  
  558. @example
  559. typeof (*x) y[4];
  560. @end example
  561.  
  562. @item
  563. This declares @code{y} as an array of pointers to characters:
  564.  
  565. @example
  566. typeof (typeof (char *)[4]) y;
  567. @end example
  568.  
  569. @noindent
  570. It is equivalent to the following traditional C declaration:
  571.  
  572. @example
  573. char *y[4];
  574. @end example
  575.  
  576. To see the meaning of the declaration using @code{typeof}, and why it
  577. might be a useful way to write, let's rewrite it with these macros:
  578.  
  579. @example
  580. #define pointer(T)  typeof(T *)
  581. #define array(T, N) typeof(T [N])
  582. @end example
  583.  
  584. @noindent
  585. Now the declaration can be rewritten this way:
  586.  
  587. @example
  588. array (pointer (char), 4) y;
  589. @end example
  590.  
  591. @noindent
  592. Thus, @code{array (pointer (char), 4)} is the type of arrays of 4
  593. pointers to @code{char}.
  594. @end itemize
  595.  
  596. @node Lvalues
  597. @section Generalized Lvalues
  598. @cindex compound expressions as lvalues
  599. @cindex expressions, compound, as lvalues
  600. @cindex conditional expressions as lvalues
  601. @cindex expressions, conditional, as lvalues
  602. @cindex casts as lvalues
  603. @cindex generalized lvalues
  604. @cindex lvalues, generalized
  605. @cindex extensions, @code{?:}
  606. @cindex @code{?:} extensions
  607. Compound expressions, conditional expressions and casts are allowed as
  608. lvalues provided their operands are lvalues.  This means that you can take
  609. their addresses or store values into them.
  610.  
  611. Standard C++ allows compound expressions and conditional expressions as
  612. lvalues, and permits casts to reference type, so use of this extension
  613. is deprecated for C++ code.
  614.  
  615. For example, a compound expression can be assigned, provided the last
  616. expression in the sequence is an lvalue.  These two expressions are
  617. equivalent:
  618.  
  619. @example
  620. (a, b) += 5
  621. a, (b += 5)
  622. @end example
  623.  
  624. Similarly, the address of the compound expression can be taken.  These two
  625. expressions are equivalent:
  626.  
  627. @example
  628. &(a, b)
  629. a, &b
  630. @end example
  631.  
  632. A conditional expression is a valid lvalue if its type is not void and the
  633. true and false branches are both valid lvalues.  For example, these two
  634. expressions are equivalent:
  635.  
  636. @example
  637. (a ? b : c) = 5
  638. (a ? b = 5 : (c = 5))
  639. @end example
  640.  
  641. A cast is a valid lvalue if its operand is an lvalue.  A simple
  642. assignment whose left-hand side is a cast works by converting the
  643. right-hand side first to the specified type, then to the type of the
  644. inner left-hand side expression.  After this is stored, the value is
  645. converted back to the specified type to become the value of the
  646. assignment.  Thus, if @code{a} has type @code{char *}, the following two
  647. expressions are equivalent:
  648.  
  649. @example
  650. (int)a = 5
  651. (int)(a = (char *)(int)5)
  652. @end example
  653.  
  654. An assignment-with-arithmetic operation such as @samp{+=} applied to a cast
  655. performs the arithmetic using the type resulting from the cast, and then
  656. continues as in the previous case.  Therefore, these two expressions are
  657. equivalent:
  658.  
  659. @example
  660. (int)a += 5
  661. (int)(a = (char *)(int) ((int)a + 5))
  662. @end example
  663.  
  664. You cannot take the address of an lvalue cast, because the use of its
  665. address would not work out coherently.  Suppose that @code{&(int)f} were
  666. permitted, where @code{f} has type @code{float}.  Then the following
  667. statement would try to store an integer bit-pattern where a floating
  668. point number belongs:
  669.  
  670. @example
  671. *&(int)f = 1;
  672. @end example
  673.  
  674. This is quite different from what @code{(int)f = 1} would do---that
  675. would convert 1 to floating point and store it.  Rather than cause this
  676. inconsistency, we think it is better to prohibit use of @samp{&} on a cast.
  677.  
  678. If you really do want an @code{int *} pointer with the address of
  679. @code{f}, you can simply write @code{(int *)&f}.
  680.  
  681. @node Conditionals
  682. @section Conditionals with Omitted Operands
  683. @cindex conditional expressions, extensions
  684. @cindex omitted middle-operands
  685. @cindex middle-operands, omitted
  686. @cindex extensions, @code{?:}
  687. @cindex @code{?:} extensions
  688.  
  689. The middle operand in a conditional expression may be omitted.  Then
  690. if the first operand is nonzero, its value is the value of the conditional
  691. expression.
  692.  
  693. Therefore, the expression
  694.  
  695. @example
  696. x ? : y
  697. @end example
  698.  
  699. @noindent
  700. has the value of @code{x} if that is nonzero; otherwise, the value of
  701. @code{y}.
  702.  
  703. This example is perfectly equivalent to
  704.  
  705. @example
  706. x ? x : y
  707. @end example
  708.  
  709. @cindex side effect in ?:
  710. @cindex ?: side effect
  711. @noindent
  712. In this simple case, the ability to omit the middle operand is not
  713. especially useful.  When it becomes useful is when the first operand does,
  714. or may (if it is a macro argument), contain a side effect.  Then repeating
  715. the operand in the middle would perform the side effect twice.  Omitting
  716. the middle operand uses the value already computed without the undesirable
  717. effects of recomputing it.
  718.  
  719. @node Long Long
  720. @section Double-Word Integers
  721. @cindex @code{long long} data types
  722. @cindex double-word arithmetic
  723. @cindex multiprecision arithmetic
  724.  
  725. GNU C supports data types for integers that are twice as long as
  726. @code{long int}.  Simply write @code{long long int} for a signed
  727. integer, or @code{unsigned long long int} for an unsigned integer.
  728. To make an integer constant of type @code{long long int}, add the suffix
  729. @code{LL} to the integer.  To make an integer constant of type
  730. @code{unsigned long long int}, add the suffix @code{ULL} to the integer.
  731.  
  732. You can use these types in arithmetic like any other integer types.
  733. Addition, subtraction, and bitwise boolean operations on these types
  734. are open-coded on all types of machines.  Multiplication is open-coded
  735. if the machine supports fullword-to-doubleword a widening multiply
  736. instruction.  Division and shifts are open-coded only on machines that
  737. provide special support.  The operations that are not open-coded use
  738. special library routines that come with GNU CC.
  739.  
  740. There may be pitfalls when you use @code{long long} types for function
  741. arguments, unless you declare function prototypes.  If a function
  742. expects type @code{int} for its argument, and you pass a value of type
  743. @code{long long int}, confusion will result because the caller and the
  744. subroutine will disagree about the number of bytes for the argument.
  745. Likewise, if the function expects @code{long long int} and you pass
  746. @code{int}.  The best way to avoid such problems is to use prototypes.
  747.  
  748. @node Complex
  749. @section Complex Numbers
  750. @cindex complex numbers
  751.  
  752. GNU C supports complex data types.  You can declare both complex integer
  753. types and complex floating types, using the keyword @code{__complex__}.
  754.  
  755. For example, @samp{__complex__ double x;} declares @code{x} as a
  756. variable whose real part and imaginary part are both of type
  757. @code{double}.  @samp{__complex__ short int y;} declares @code{y} to
  758. have real and imaginary parts of type @code{short int}; this is not
  759. likely to be useful, but it shows that the set of complex types is
  760. complete.
  761.  
  762. To write a constant with a complex data type, use the suffix @samp{i} or
  763. @samp{j} (either one; they are equivalent).  For example, @code{2.5fi}
  764. has type @code{__complex__ float} and @code{3i} has type
  765. @code{__complex__ int}.  Such a constant always has a pure imaginary
  766. value, but you can form any complex value you like by adding one to a
  767. real constant.
  768.  
  769. To extract the real part of a complex-valued expression @var{exp}, write
  770. @code{__real__ @var{exp}}.  Likewise, use @code{__imag__} to
  771. extract the imaginary part.
  772.  
  773. The operator @samp{~} performs complex conjugation when used on a value
  774. with a complex type.
  775.  
  776. GNU CC can allocate complex automatic variables in a noncontiguous
  777. fashion; it's even possible for the real part to be in a register while
  778. the imaginary part is on the stack (or vice-versa).  None of the
  779. supported debugging info formats has a way to represent noncontiguous
  780. allocation like this, so GNU CC describes a noncontiguous complex
  781. variable as if it were two separate variables of noncomplex type.
  782. If the variable's actual name is @code{foo}, the two fictitious 
  783. variables are named @code{foo$real} and @code{foo$imag}.  You can
  784. examine and set these two fictitious variables with your debugger.
  785.  
  786. A future version of GDB will know how to recognize such pairs and treat
  787. them as a single variable with a complex type.
  788.  
  789. @node Zero Length
  790. @section Arrays of Length Zero
  791. @cindex arrays of length zero
  792. @cindex zero-length arrays
  793. @cindex length-zero arrays
  794.  
  795. Zero-length arrays are allowed in GNU C.  They are very useful as the last
  796. element of a structure which is really a header for a variable-length
  797. object:
  798.  
  799. @example
  800. struct line @{
  801.   int length;
  802.   char contents[0];
  803. @};
  804.  
  805. @{
  806.   struct line *thisline = (struct line *)
  807.     malloc (sizeof (struct line) + this_length);
  808.   thisline->length = this_length;
  809. @}
  810. @end example
  811.  
  812. In standard C, you would have to give @code{contents} a length of 1, which
  813. means either you waste space or complicate the argument to @code{malloc}.
  814.  
  815. @node Variable Length
  816. @section Arrays of Variable Length
  817. @cindex variable-length arrays
  818. @cindex arrays of variable length
  819.  
  820. Variable-length automatic arrays are allowed in GNU C.  These arrays are
  821. declared like any other automatic arrays, but with a length that is not
  822. a constant expression.  The storage is allocated at the point of
  823. declaration and deallocated when the brace-level is exited.  For
  824. example:
  825.  
  826. @example
  827. FILE *
  828. concat_fopen (char *s1, char *s2, char *mode)
  829. @{
  830.   char str[strlen (s1) + strlen (s2) + 1];
  831.   strcpy (str, s1);
  832.   strcat (str, s2);
  833.   return fopen (str, mode);
  834. @}
  835. @end example
  836.  
  837. @cindex scope of a variable length array
  838. @cindex variable-length array scope
  839. @cindex deallocating variable length arrays
  840. Jumping or breaking out of the scope of the array name deallocates the
  841. storage.  Jumping into the scope is not allowed; you get an error
  842. message for it.
  843.  
  844. @cindex @code{alloca} vs variable-length arrays
  845. You can use the function @code{alloca} to get an effect much like
  846. variable-length arrays.  The function @code{alloca} is available in
  847. many other C implementations (but not in all).  On the other hand,
  848. variable-length arrays are more elegant.
  849.  
  850. There are other differences between these two methods.  Space allocated
  851. with @code{alloca} exists until the containing @emph{function} returns.
  852. The space for a variable-length array is deallocated as soon as the array
  853. name's scope ends.  (If you use both variable-length arrays and
  854. @code{alloca} in the same function, deallocation of a variable-length array
  855. will also deallocate anything more recently allocated with @code{alloca}.)
  856.  
  857. You can also use variable-length arrays as arguments to functions:
  858.  
  859. @example
  860. struct entry
  861. tester (int len, char data[len][len])
  862. @{
  863.   @dots{}
  864. @}
  865. @end example
  866.  
  867. The length of an array is computed once when the storage is allocated
  868. and is remembered for the scope of the array in case you access it with
  869. @code{sizeof}.
  870.  
  871. If you want to pass the array first and the length afterward, you can
  872. use a forward declaration in the parameter list---another GNU extension.
  873.  
  874. @example
  875. struct entry
  876. tester (int len; char data[len][len], int len)
  877. @{
  878.   @dots{}
  879. @}
  880. @end example
  881.  
  882. @cindex parameter forward declaration
  883. The @samp{int len} before the semicolon is a @dfn{parameter forward
  884. declaration}, and it serves the purpose of making the name @code{len}
  885. known when the declaration of @code{data} is parsed.
  886.  
  887. You can write any number of such parameter forward declarations in the
  888. parameter list.  They can be separated by commas or semicolons, but the
  889. last one must end with a semicolon, which is followed by the ``real''
  890. parameter declarations.  Each forward declaration must match a ``real''
  891. declaration in parameter name and data type.
  892.  
  893. @node Macro Varargs
  894. @section Macros with Variable Numbers of Arguments
  895. @cindex variable number of arguments
  896. @cindex macro with variable arguments
  897. @cindex rest argument (in macro)
  898.  
  899. In GNU C, a macro can accept a variable number of arguments, much as a
  900. function can.  The syntax for defining the macro looks much like that
  901. used for a function.  Here is an example:
  902.  
  903. @example
  904. #define eprintf(format, args...)  \
  905.  fprintf (stderr, format , ## args)
  906. @end example
  907.  
  908. Here @code{args} is a @dfn{rest argument}: it takes in zero or more
  909. arguments, as many as the call contains.  All of them plus the commas
  910. between them form the value of @code{args}, which is substituted into
  911. the macro body where @code{args} is used.  Thus, we have this expansion:
  912.  
  913. @example
  914. eprintf ("%s:%d: ", input_file_name, line_number)
  915. @expansion{}
  916. fprintf (stderr, "%s:%d: " , input_file_name, line_number)
  917. @end example
  918.  
  919. @noindent
  920. Note that the comma after the string constant comes from the definition
  921. of @code{eprintf}, whereas the last comma comes from the value of
  922. @code{args}.
  923.  
  924. The reason for using @samp{##} is to handle the case when @code{args}
  925. matches no arguments at all.  In this case, @code{args} has an empty
  926. value.  In this case, the second comma in the definition becomes an
  927. embarrassment: if it got through to the expansion of the macro, we would
  928. get something like this:
  929.  
  930. @example
  931. fprintf (stderr, "success!\n" , )
  932. @end example
  933.  
  934. @noindent
  935. which is invalid C syntax.  @samp{##} gets rid of the comma, so we get
  936. the following instead:
  937.  
  938. @example
  939. fprintf (stderr, "success!\n")
  940. @end example
  941.  
  942. This is a special feature of the GNU C preprocessor: @samp{##} before a
  943. rest argument that is empty discards the preceding sequence of
  944. non-whitespace characters from the macro definition.  (If another macro
  945. argument precedes, none of it is discarded.)
  946.  
  947. It might be better to discard the last preprocessor token instead of the
  948. last preceding sequence of non-whitespace characters; in fact, we may
  949. someday change this feature to do so.  We advise you to write the macro
  950. definition so that the preceding sequence of non-whitespace characters
  951. is just a single token, so that the meaning will not change if we change
  952. the definition of this feature.
  953.  
  954. @node Subscripting
  955. @section Non-Lvalue Arrays May Have Subscripts
  956. @cindex subscripting
  957. @cindex arrays, non-lvalue
  958.  
  959. @cindex subscripting and function values
  960. Subscripting is allowed on arrays that are not lvalues, even though the
  961. unary @samp{&} operator is not.  For example, this is valid in GNU C though
  962. not valid in other C dialects:
  963.  
  964. @example
  965. @group
  966. struct foo @{int a[4];@};
  967.  
  968. struct foo f();
  969.  
  970. bar (int index)
  971. @{
  972.   return f().a[index];
  973. @}
  974. @end group
  975. @end example
  976.  
  977. @node Pointer Arith
  978. @section Arithmetic on @code{void}- and Function-Pointers
  979. @cindex void pointers, arithmetic
  980. @cindex void, size of pointer to
  981. @cindex function pointers, arithmetic
  982. @cindex function, size of pointer to
  983.  
  984. In GNU C, addition and subtraction operations are supported on pointers to
  985. @code{void} and on pointers to functions.  This is done by treating the
  986. size of a @code{void} or of a function as 1.
  987.  
  988. A consequence of this is that @code{sizeof} is also allowed on @code{void}
  989. and on function types, and returns 1.
  990.  
  991. The option @samp{-Wpointer-arith} requests a warning if these extensions
  992. are used.
  993.  
  994. @node Initializers
  995. @section Non-Constant Initializers
  996. @cindex initializers, non-constant
  997. @cindex non-constant initializers
  998.  
  999. As in standard C++, the elements of an aggregate initializer for an
  1000. automatic variable are not required to be constant expressions in GNU C.
  1001. Here is an example of an initializer with run-time varying elements:
  1002.  
  1003. @example
  1004. foo (float f, float g)
  1005. @{
  1006.   float beat_freqs[2] = @{ f-g, f+g @};
  1007.   @dots{}
  1008. @}
  1009. @end example
  1010.  
  1011. @node Constructors
  1012. @section Constructor Expressions
  1013. @cindex constructor expressions
  1014. @cindex initializations in expressions
  1015. @cindex structures, constructor expression
  1016. @cindex expressions, constructor 
  1017.  
  1018. GNU C supports constructor expressions.  A constructor looks like
  1019. a cast containing an initializer.  Its value is an object of the
  1020. type specified in the cast, containing the elements specified in
  1021. the initializer.
  1022.  
  1023. Usually, the specified type is a structure.  Assume that
  1024. @code{struct foo} and @code{structure} are declared as shown:
  1025.  
  1026. @example
  1027. struct foo @{int a; char b[2];@} structure;
  1028. @end example
  1029.  
  1030. @noindent
  1031. Here is an example of constructing a @code{struct foo} with a constructor:
  1032.  
  1033. @example
  1034. structure = ((struct foo) @{x + y, 'a', 0@});
  1035. @end example
  1036.  
  1037. @noindent
  1038. This is equivalent to writing the following:
  1039.  
  1040. @example
  1041. @{
  1042.   struct foo temp = @{x + y, 'a', 0@};
  1043.   structure = temp;
  1044. @}
  1045. @end example
  1046.  
  1047. You can also construct an array.  If all the elements of the constructor
  1048. are (made up of) simple constant expressions, suitable for use in
  1049. initializers, then the constructor is an lvalue and can be coerced to a
  1050. pointer to its first element, as shown here:
  1051.  
  1052. @example
  1053. char **foo = (char *[]) @{ "x", "y", "z" @};
  1054. @end example
  1055.  
  1056. Array constructors whose elements are not simple constants are
  1057. not very useful, because the constructor is not an lvalue.  There
  1058. are only two valid ways to use it: to subscript it, or initialize
  1059. an array variable with it.  The former is probably slower than a
  1060. @code{switch} statement, while the latter does the same thing an
  1061. ordinary C initializer would do.  Here is an example of
  1062. subscripting an array constructor:
  1063.  
  1064. @example
  1065. output = ((int[]) @{ 2, x, 28 @}) [input];
  1066. @end example
  1067.  
  1068. Constructor expressions for scalar types and union types are is
  1069. also allowed, but then the constructor expression is equivalent
  1070. to a cast.
  1071.  
  1072. @node Labeled Elements
  1073. @section Labeled Elements in Initializers
  1074. @cindex initializers with labeled elements
  1075. @cindex labeled elements in initializers
  1076. @cindex case labels in initializers
  1077.  
  1078. Standard C requires the elements of an initializer to appear in a fixed
  1079. order, the same as the order of the elements in the array or structure
  1080. being initialized.
  1081.  
  1082. In GNU C you can give the elements in any order, specifying the array
  1083. indices or structure field names they apply to.  This extension is not
  1084. implemented in GNU C++.
  1085.  
  1086. To specify an array index, write @samp{[@var{index}]} or
  1087. @samp{[@var{index}] =} before the element value.  For example,
  1088.  
  1089. @example
  1090. int a[6] = @{ [4] 29, [2] = 15 @};
  1091. @end example
  1092.  
  1093. @noindent
  1094. is equivalent to
  1095.  
  1096. @example
  1097. int a[6] = @{ 0, 0, 15, 0, 29, 0 @};
  1098. @end example
  1099.  
  1100. @noindent
  1101. The index values must be constant expressions, even if the array being
  1102. initialized is automatic.
  1103.  
  1104. To initialize a range of elements to the same value, write
  1105. @samp{[@var{first} ... @var{last}] = @var{value}}.  For example,
  1106.  
  1107. @example
  1108. int widths[] = @{ [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 @};
  1109. @end example
  1110.  
  1111. @noindent
  1112. Note that the length of the array is the highest value specified
  1113. plus one.
  1114.  
  1115. In a structure initializer, specify the name of a field to initialize
  1116. with @samp{@var{fieldname}:} before the element value.  For example,
  1117. given the following structure, 
  1118.  
  1119. @example
  1120. struct point @{ int x, y; @};
  1121. @end example
  1122.  
  1123. @noindent
  1124. the following initialization
  1125.  
  1126. @example
  1127. struct point p = @{ y: yvalue, x: xvalue @};
  1128. @end example
  1129.  
  1130. @noindent
  1131. is equivalent to
  1132.  
  1133. @example
  1134. struct point p = @{ xvalue, yvalue @};
  1135. @end example
  1136.  
  1137. Another syntax which has the same meaning is @samp{.@var{fieldname} =}.,
  1138. as shown here:
  1139.  
  1140. @example
  1141. struct point p = @{ .y = yvalue, .x = xvalue @};
  1142. @end example
  1143.  
  1144. You can also use an element label (with either the colon syntax or the
  1145. period-equal syntax) when initializing a union, to specify which element
  1146. of the union should be used.  For example,
  1147.  
  1148. @example
  1149. union foo @{ int i; double d; @};
  1150.  
  1151. union foo f = @{ d: 4 @};
  1152. @end example
  1153.  
  1154. @noindent
  1155. will convert 4 to a @code{double} to store it in the union using
  1156. the second element.  By contrast, casting 4 to type @code{union foo}
  1157. would store it into the union as the integer @code{i}, since it is
  1158. an integer.  (@xref{Cast to Union}.)
  1159.  
  1160. You can combine this technique of naming elements with ordinary C
  1161. initialization of successive elements.  Each initializer element that
  1162. does not have a label applies to the next consecutive element of the
  1163. array or structure.  For example,
  1164.  
  1165. @example
  1166. int a[6] = @{ [1] = v1, v2, [4] = v4 @};
  1167. @end example
  1168.  
  1169. @noindent
  1170. is equivalent to
  1171.  
  1172. @example
  1173. int a[6] = @{ 0, v1, v2, 0, v4, 0 @};
  1174. @end example
  1175.  
  1176. Labeling the elements of an array initializer is especially useful
  1177. when the indices are characters or belong to an @code{enum} type.
  1178. For example:
  1179.  
  1180. @example
  1181. int whitespace[256]
  1182.   = @{ [' '] = 1, ['\t'] = 1, ['\h'] = 1,
  1183.       ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 @};
  1184. @end example
  1185.  
  1186. @node Case Ranges
  1187. @section Case Ranges
  1188. @cindex case ranges
  1189. @cindex ranges in case statements
  1190.  
  1191. You can specify a range of consecutive values in a single @code{case} label,
  1192. like this:
  1193.  
  1194. @example
  1195. case @var{low} ... @var{high}:
  1196. @end example
  1197.  
  1198. @noindent
  1199. This has the same effect as the proper number of individual @code{case}
  1200. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  1201.  
  1202. This feature is especially useful for ranges of ASCII character codes:
  1203.  
  1204. @example
  1205. case 'A' ... 'Z':
  1206. @end example
  1207.  
  1208. @strong{Be careful:} Write spaces around the @code{...}, for otherwise
  1209. it may be parsed wrong when you use it with integer values.  For example,
  1210. write this:
  1211.  
  1212. @example
  1213. case 1 ... 5:
  1214. @end example
  1215.  
  1216. @noindent 
  1217. rather than this:
  1218.  
  1219. @example
  1220. case 1...5:
  1221. @end example
  1222.  
  1223. @node Cast to Union
  1224. @section Cast to a Union Type
  1225. @cindex cast to a union
  1226. @cindex union, casting to a 
  1227.  
  1228. A cast to union type is similar to other casts, except that the type
  1229. specified is a union type.  You can specify the type either with
  1230. @code{union @var{tag}} or with a typedef name.  A cast to union is actually
  1231. a constructor though, not a cast, and hence does not yield an lvalue like
  1232. normal casts.  (@xref{Constructors}.)
  1233.  
  1234. The types that may be cast to the union type are those of the members
  1235. of the union.  Thus, given the following union and variables:
  1236.  
  1237. @example
  1238. union foo @{ int i; double d; @};
  1239. int x;
  1240. double y;
  1241. @end example
  1242.  
  1243. @noindent
  1244. both @code{x} and @code{y} can be cast to type @code{union} foo.
  1245.  
  1246. Using the cast as the right-hand side of an assignment to a variable of
  1247. union type is equivalent to storing in a member of the union:
  1248.  
  1249. @example
  1250. union foo u;
  1251. @dots{}
  1252. u = (union foo) x  @equiv{}  u.i = x
  1253. u = (union foo) y  @equiv{}  u.d = y
  1254. @end example
  1255.  
  1256. You can also use the union cast as a function argument:
  1257.  
  1258. @example
  1259. void hack (union foo);
  1260. @dots{}
  1261. hack ((union foo) x);
  1262. @end example
  1263.  
  1264. @node Function Attributes
  1265. @section Declaring Attributes of Functions
  1266. @cindex function attributes
  1267. @cindex declaring attributes of functions
  1268. @cindex functions that never return
  1269. @cindex functions that have no side effects
  1270. @cindex functions in arbitrary sections
  1271. @cindex @code{volatile} applied to function
  1272. @cindex @code{const} applied to function
  1273. @cindex functions with @code{printf} or @code{scanf} style arguments
  1274.  
  1275. In GNU C, you declare certain things about functions called in your program
  1276. which help the compiler optimize function calls and check your code more
  1277. carefully.
  1278.  
  1279. The keyword @code{__attribute__} allows you to specify special
  1280. attributes when making a declaration.  This keyword is followed by an
  1281. attribute specification inside double parentheses.  Four attributes,
  1282. @code{noreturn}, @code{const}, @code{format}, and @code{section} are
  1283. currently defined for functions.  Other attributes, including @code{section}
  1284. are supported for variables declarations
  1285. (@pxref{Variable Attributes}).
  1286.  
  1287. You may also specify attributes with @samp{__} preceeding and following
  1288. each keyword.  This allows you to use them in header files without
  1289. being concerned about a possible macro of the same name.  For example,
  1290. you may use @code{__noreturn__} instead of @code{noreturn}.
  1291.  
  1292. @table @code
  1293. @cindex @code{noreturn} function attribute
  1294. @item noreturn
  1295. A few standard library functions, such as @code{abort} and @code{exit},
  1296. cannot return.  GNU CC knows this automatically.  Some programs define
  1297. their own functions that never return.  You can declare them
  1298. @code{noreturn} to tell the compiler this fact.  For example,
  1299.  
  1300. @smallexample
  1301. void fatal () __attribute__ ((noreturn));
  1302.  
  1303. void
  1304. fatal (@dots{})
  1305. @{
  1306.   @dots{} /* @r{Print error message.} */ @dots{}
  1307.   exit (1);
  1308. @}
  1309. @end smallexample
  1310.  
  1311. The @code{noreturn} keyword tells the compiler to assume that
  1312. @code{fatal} cannot return.  It can then optimize without regard to what
  1313. would happen if @code{fatal} ever did return.  This makes slightly
  1314. better code.  More importantly, it helps avoid spurious warnings of
  1315. uninitialized variables.
  1316.  
  1317. Do not assume that registers saved by the calling function are
  1318. restored before calling the @code{noreturn} function.
  1319.  
  1320. It does not make sense for a @code{noreturn} function to have a return
  1321. type other than @code{void}.
  1322.  
  1323. The attribute @code{noreturn} is not implemented in GNU C versions
  1324. earlier than 2.5.  An alternative way to declare that a function does
  1325. not return, which works in the current version and in some older
  1326. versions, is as follows:
  1327.  
  1328. @smallexample  
  1329. typedef void voidfn ();
  1330.  
  1331. volatile voidfn fatal;
  1332. @end smallexample
  1333.  
  1334. @cindex @code{const} function attribute
  1335. @item const
  1336. Many functions do not examine any values except their arguments, and
  1337. have no effects except the return value.  Such a function can be subject
  1338. to common subexpression elimination and loop optimization just as an
  1339. arithmetic operator would be.  These functions should be declared
  1340. with the attribute @code{const}.  For example,
  1341.  
  1342. @smallexample
  1343. int square (int) __attribute__ ((const));
  1344. @end smallexample
  1345.  
  1346. @noindent
  1347. says that the hypothetical function @code{square} is safe to call
  1348. fewer times than the program says.
  1349.  
  1350. The attribute @code{const} is not implemented in GNU C versions earlier
  1351. than 2.5.  An alternative way to declare that a function has no side
  1352. effects, which works in the current version and in some older versions,
  1353. is as follows:
  1354.  
  1355. @smallexample
  1356. typedef int intfn ();
  1357.  
  1358. extern const intfn square;
  1359. @end smallexample
  1360.  
  1361. This approach does not work in GNU C++ from 2.6.0 on, since the language
  1362. specifies that the @samp{const} must be attached to the return value.
  1363.  
  1364. @cindex pointer arguments
  1365. Note that a function that has pointer arguments and examines the data
  1366. pointed to must @emph{not} be declared @code{const}.  Likewise, a
  1367. function that calls a non-@code{const} function usually must not be
  1368. @code{const}.  It does not make sense for a @code{const} function to
  1369. return @code{void}.
  1370.  
  1371. @item format (@var{archetype}, @var{string-index}, @var{first-to-check})
  1372. @cindex @code{format} function attribute
  1373. The @code{format} attribute specifies that a function takes @code{printf}
  1374. or @code{scanf} style arguments which should be type-checked against a
  1375. format string.  For example, the declaration:
  1376.  
  1377. @smallexample
  1378. extern int
  1379. my_printf (void *my_object, const char *my_format, ...)
  1380.       __attribute__ ((format (printf, 2, 3)));
  1381. @end smallexample
  1382.  
  1383. @noindent
  1384. causes the compiler to check the arguments in calls to @code{my_printf}
  1385. for consistency with the @code{printf} style format string argument
  1386. @code{my_format}.
  1387.  
  1388. The parameter @var{archetype} determines how the format string is
  1389. interpreted, and should be either @code{printf} or @code{scanf}.  The
  1390. parameter @var{string-index} specifies which argument is the format
  1391. string argument (starting from 1), while @var{first-to-check} is the
  1392. number of the first argument to check against the format string.  For
  1393. functions where the arguments are not available to be checked (such as
  1394. @code{vprintf}), specify the third parameter as zero.  In this case the
  1395. compiler only checks the format string for consistency.
  1396.  
  1397. In the example above, the format string (@code{my_format}) is the second
  1398. argument of the function @code{my_print}, and the arguments to check
  1399. start with the third argument, so the correct parameters for the format
  1400. attribute are 2 and 3.
  1401.  
  1402. The @code{format} attribute allows you to identify your own functions
  1403. which take format strings as arguments, so that GNU CC can check the
  1404. calls to these functions for errors.  The compiler always checks formats
  1405. for the ANSI library functions @code{printf}, @code{fprintf},
  1406. @code{sprintf}, @code{scanf}, @code{fscanf}, @code{sscanf},
  1407. @code{vprintf}, @code{vfprintf} and @code{vsprintf} whenever such
  1408. warnings are requested (using @samp{-Wformat}), so there is no need to
  1409. modify the header file @file{stdio.h}.
  1410.  
  1411. @item section ("section-name")
  1412. @cindex @code{section} function attribute
  1413. Normally, the compiler places the code it generates in the @code{text} section.
  1414. Sometimes, however, you need additional sections, or you need certain
  1415. particular functions to appear in special sections.  The @code{section}
  1416. attribute specifies that a function lives in a particular section.
  1417. For example, the declaration:
  1418.  
  1419. @smallexample
  1420. extern void foobar (void) __attribute__ ((section (".init")));
  1421. @end smallexample
  1422.  
  1423. @noindent
  1424. puts the function @code{foobar} in the @code{.init} section.
  1425.  
  1426. Some file formats do not support arbitrary sections so the @code{section}
  1427. attribute is not available on all platforms.
  1428. If you need to map the entire contents of a module to a particular
  1429. section, consider using the facilities of the linker instead.
  1430. @end table
  1431.  
  1432. You can specify multiple attributes in a declaration by separating them
  1433. by commas within the double parentheses or by immediately following an
  1434. attribute declaration with another attribute declaration.
  1435.  
  1436. @cindex @code{#pragma}, reason for not using
  1437. @cindex pragma, reason for not using
  1438. Some people object to the @code{__attribute__} feature, suggesting that ANSI C's
  1439. @code{#pragma} should be used instead.  There are two reasons for not
  1440. doing this.
  1441.  
  1442. @enumerate
  1443. @item
  1444. It is impossible to generate @code{#pragma} commands from a macro.
  1445.  
  1446. @item
  1447. There is no telling what the same @code{#pragma} might mean in another
  1448. compiler.
  1449. @end enumerate
  1450.  
  1451. These two reasons apply to almost any application that might be proposed
  1452. for @code{#pragma}.  It is basically a mistake to use @code{#pragma} for
  1453. @emph{anything}.
  1454.  
  1455. @node Function Prototypes
  1456. @section Prototypes and Old-Style Function Definitions
  1457. @cindex function prototype declarations
  1458. @cindex old-style function definitions
  1459. @cindex promotion of formal parameters
  1460.  
  1461. GNU C extends ANSI C to allow a function prototype to override a later
  1462. old-style non-prototype definition.  Consider the following example:
  1463.  
  1464. @example
  1465. /* @r{Use prototypes unless the compiler is old-fashioned.}  */
  1466. #if __STDC__
  1467. #define P(x) x
  1468. #else
  1469. #define P(x) ()
  1470. #endif
  1471.  
  1472. /* @r{Prototype function declaration.}  */
  1473. int isroot P((uid_t));
  1474.  
  1475. /* @r{Old-style function definition.}  */
  1476. int
  1477. isroot (x)   /* ??? lossage here ??? */
  1478.      uid_t x;
  1479. @{
  1480.   return x == 0;
  1481. @}
  1482. @end example
  1483.  
  1484. Suppose the type @code{uid_t} happens to be @code{short}.  ANSI C does
  1485. not allow this example, because subword arguments in old-style
  1486. non-prototype definitions are promoted.  Therefore in this example the
  1487. function definition's argument is really an @code{int}, which does not
  1488. match the prototype argument type of @code{short}.
  1489.  
  1490. This restriction of ANSI C makes it hard to write code that is portable
  1491. to traditional C compilers, because the programmer does not know
  1492. whether the @code{uid_t} type is @code{short}, @code{int}, or
  1493. @code{long}.  Therefore, in cases like these GNU C allows a prototype
  1494. to override a later old-style definition.  More precisely, in GNU C, a
  1495. function prototype argument type overrides the argument type specified
  1496. by a later old-style definition if the former type is the same as the
  1497. latter type before promotion.  Thus in GNU C the above example is
  1498. equivalent to the following:
  1499.  
  1500. @example
  1501. int isroot (uid_t);
  1502.  
  1503. int
  1504. isroot (uid_t x)
  1505. @{
  1506.   return x == 0;
  1507. @}
  1508. @end example
  1509.  
  1510. GNU C++ does not support old-style function definitions, so this
  1511. extension is irrelevant.
  1512.  
  1513. @node Dollar Signs
  1514. @section Dollar Signs in Identifier Names
  1515. @cindex $
  1516. @cindex dollar signs in identifier names
  1517. @cindex identifier names, dollar signs in
  1518.  
  1519. In GNU C, you may use dollar signs in identifier names.  This is because
  1520. many traditional C implementations allow such identifiers.
  1521.  
  1522. On some machines, dollar signs are allowed in identifiers if you specify
  1523. @w{@samp{-traditional}}.  On a few systems they are allowed by default,
  1524. even if you do not use @w{@samp{-traditional}}.  But they are never
  1525. allowed if you specify @w{@samp{-ansi}}.
  1526.  
  1527. There are certain ANSI C programs (obscure, to be sure) that would
  1528. compile incorrectly if dollar signs were permitted in identifiers.  For
  1529. example:
  1530.  
  1531. @example
  1532. #define foo(a) #a
  1533. #define lose(b) foo (b)
  1534. #define test$
  1535. lose (test)
  1536. @end example
  1537.  
  1538. @node Character Escapes
  1539. @section The Character @key{ESC} in Constants
  1540.  
  1541. You can use the sequence @samp{\e} in a string or character constant to
  1542. stand for the ASCII character @key{ESC}.
  1543.  
  1544. @node Alignment
  1545. @section Inquiring on Alignment of Types or Variables
  1546. @cindex alignment
  1547. @cindex type alignment
  1548. @cindex variable alignment
  1549.  
  1550. The keyword @code{__alignof__} allows you to inquire about how an object
  1551. is aligned, or the minimum alignment usually required by a type.  Its
  1552. syntax is just like @code{sizeof}.
  1553.  
  1554. For example, if the target machine requires a @code{double} value to be
  1555. aligned on an 8-byte boundary, then @code{__alignof__ (double)} is 8.
  1556. This is true on many RISC machines.  On more traditional machine
  1557. designs, @code{__alignof__ (double)} is 4 or even 2.
  1558.  
  1559. Some machines never actually require alignment; they allow reference to any
  1560. data type even at an odd addresses.  For these machines, @code{__alignof__}
  1561. reports the @emph{recommended} alignment of a type.
  1562.  
  1563. When the operand of @code{__alignof__} is an lvalue rather than a type, the
  1564. value is the largest alignment that the lvalue is known to have.  It may
  1565. have this alignment as a result of its data type, or because it is part of
  1566. a structure and inherits alignment from that structure.  For example, after
  1567. this declaration:
  1568.  
  1569. @example
  1570. struct foo @{ int x; char y; @} foo1;
  1571. @end example
  1572.  
  1573. @noindent
  1574. the value of @code{__alignof__ (foo1.y)} is probably 2 or 4, the same as
  1575. @code{__alignof__ (int)}, even though the data type of @code{foo1.y}
  1576. does not itself demand any alignment.@refill
  1577.  
  1578. A related feature which lets you specify the alignment of an object is
  1579. @code{__attribute__ ((aligned (@var{alignment})))}; see the following
  1580. section.
  1581.  
  1582. @node Variable Attributes
  1583. @section Specifying Attributes of Variables
  1584. @cindex attribute of variables
  1585. @cindex variable attributes
  1586.  
  1587. The keyword @code{__attribute__} allows you to specify special
  1588. attributes of variables or structure fields.  This keyword is followed
  1589. by an attribute specification inside double parentheses.  Four
  1590. attributes are currently defined for variables: @code{aligned},
  1591. @code{mode}, @code{packed}, and @code{section}.  Other attributes are
  1592. defined for functions, and thus not documented here;
  1593. see @ref{Function Attributes}.
  1594.  
  1595. You may also specify attributes with @samp{__} preceeding and following
  1596. each keyword.  This allows you to use them in header files without
  1597. being concerned about a possible macro of the same name.  For example,
  1598. you may use @code{__aligned__} instead of @code{aligned}.
  1599.  
  1600. @table @code
  1601. @cindex @code{aligned} attribute
  1602. @item aligned (@var{alignment})
  1603. This attribute specifies a minimum alignment for the variable or
  1604. structure field, measured in bytes.  For example, the declaration:
  1605.  
  1606. @smallexample
  1607. int x __attribute__ ((aligned (16))) = 0;
  1608. @end smallexample
  1609.  
  1610. @noindent
  1611. causes the compiler to allocate the global variable @code{x} on a
  1612. 16-byte boundary.  On a 68040, this could be used in conjunction with
  1613. an @code{asm} expression to access the @code{move16} instruction which
  1614. requires 16-byte aligned operands.
  1615.  
  1616. You can also specify the alignment of structure fields.  For example, to
  1617. create a double-word aligned @code{int} pair, you could write:
  1618.  
  1619. @smallexample
  1620. struct foo @{ int x[2] __attribute__ ((aligned (8))); @};
  1621. @end smallexample
  1622.  
  1623. @noindent
  1624. This is an alternative to creating a union with a @code{double} member
  1625. that forces the union to be double-word aligned.
  1626.  
  1627. It is not possible to specify the alignment of functions; the alignment
  1628. of functions is determined by the machine's requirements and cannot be
  1629. changed.  You cannot specify alignment for a typedef name because such a
  1630. name is just an alias, not a distinct type.
  1631.  
  1632. The @code{aligned} attribute can only increase the alignment; but you
  1633. can decrease it by specifying @code{packed} as well.  See below.
  1634.  
  1635. The linker of your operating system imposes a maximum alignment.  If the
  1636. linker aligns each object file on a four byte boundary, then it is
  1637. beyond the compiler's power to cause anything to be aligned to a larger
  1638. boundary than that.  For example, if  the linker happens to put this object
  1639. file at address 136 (eight more than a multiple of 64), then the compiler
  1640. cannot guarantee an alignment of more than 8 just by aligning variables in
  1641. the object file.
  1642.  
  1643. @item mode (@var{mode})
  1644. @cindex @code{mode} attribute
  1645. This attribute specifies the data type for the declaration---whichever
  1646. type corresponds to the mode @var{mode}.  This in effect lets you
  1647. request an integer or floating point type according to its width.
  1648.  
  1649. @item packed
  1650. @cindex @code{packed} attribute
  1651. The @code{packed} attribute specifies that a variable or structure field
  1652. should have the smallest possible alignment---one byte for a variable,
  1653. and one bit for a field, unless you specify a larger value with the
  1654. @code{aligned} attribute.
  1655.  
  1656. Here is a structure in which the field @code{x} is packed, so that it
  1657. immediately follows @code{a}:
  1658.  
  1659. @example
  1660. struct foo
  1661. @{
  1662.   char a;
  1663.   int x[2] __attribute__ ((packed));
  1664. @};
  1665. @end example
  1666.  
  1667. @item section ("section-name")
  1668. @cindex @code{section} variable attribute
  1669. Normally, the compiler places the objects it generates in sections like
  1670. @code{data} and @code{bss}.  Sometimes, however, you need additional sections,
  1671. or you need certain particular variables to appear in special sections,
  1672. for example to map to special hardware.  The @code{section}
  1673. attribute specifies that a variable (or function) lives in a particular
  1674. section.  For example, this small program uses several specific section names:
  1675.  
  1676. @smallexample
  1677. struct duart a __attribute__ ((section ("DUART_A"))) = @{ 0 @};
  1678. struct duart b __attribute__ ((section ("DUART_B"))) = @{ 0 @};
  1679. char stack[10000] __attribute__ ((section ("STACK"))) = @{ 0 @};
  1680. int init_data_copy __attribute__ ((section ("INITDATACOPY"))) = 0;
  1681.  
  1682. main()
  1683. @{
  1684.   /* Initialize stack pointer */
  1685.   init_sp (stack + sizeof (stack));
  1686.  
  1687.   /* Initialize initialized data */
  1688.   memcpy (&init_data_copy, &data, &edata - &data);
  1689.  
  1690.   /* Turn on the serial ports */
  1691.   init_duart (&a);
  1692.   init_duart (&b);
  1693. @}
  1694. @end smallexample
  1695.  
  1696. @noindent
  1697. Use the @code{section} attribute with an @emph{initialized} definition
  1698. of a @emph{global} variable, as shown in the example.  GNU CC issues
  1699. a warning and otherwise ignores the @code{section} attribute in
  1700. uninitialized variable declarations.
  1701.  
  1702. You may only use the @code{section} attribute with a fully initialized
  1703. global definition because of the way linkers work.
  1704. The linker requires each object be defined once, with the exception that
  1705. uninitialized variables tentatively go in the @code{common} (or @code{bss})
  1706. section and can be multiply "defined".
  1707.  
  1708. Some file formats do not support arbitrary sections so the @code{section}
  1709. attribute is not available on all platforms.
  1710. If you need to map the entire contents of a module to a particular
  1711. section, consider using the facilities of the linker instead.
  1712.  
  1713. @item transparent_union
  1714. This attribute, attached to a function argument variable which is a
  1715. union, means to pass the argument in the same way that the first union
  1716. alternative would be passed.  You can also use this attribute on a
  1717. @code{typedef} for a union data type; then it applies to all function
  1718. arguments with that type.
  1719. @end table
  1720.  
  1721. To specify multiple attributes, separate them by commas within the
  1722. double parentheses: for example, @samp{__attribute__ ((aligned (16),
  1723. packed))}.
  1724.  
  1725. @node Inline
  1726. @section An Inline Function is As Fast As a Macro
  1727. @cindex inline functions
  1728. @cindex integrating function code
  1729. @cindex open coding
  1730. @cindex macros, inline alternative
  1731.  
  1732. By declaring a function @code{inline}, you can direct GNU CC to
  1733. integrate that function's code into the code for its callers.  This
  1734. makes execution faster by eliminating the function-call overhead; in
  1735. addition, if any of the actual argument values are constant, their known
  1736. values may permit simplifications at compile time so that not all of the
  1737. inline function's code needs to be included.  The effect on code size is
  1738. less predictable; object code may be larger or smaller with function
  1739. inlining, depending on the particular case.  Inlining of functions is an
  1740. optimization and it really ``works'' only in optimizing compilation.  If
  1741. you don't use @samp{-O}, no function is really inline.
  1742.  
  1743. To declare a function inline, use the @code{inline} keyword in its
  1744. declaration, like this:
  1745.  
  1746. @example
  1747. inline int
  1748. inc (int *a)
  1749. @{
  1750.   (*a)++;
  1751. @}
  1752. @end example
  1753.  
  1754. (If you are writing a header file to be included in ANSI C programs, write
  1755. @code{__inline__} instead of @code{inline}.  @xref{Alternate Keywords}.)
  1756.  
  1757. You can also make all ``simple enough'' functions inline with the option
  1758. @samp{-finline-functions}.  Note that certain usages in a function
  1759. definition can make it unsuitable for inline substitution.
  1760.  
  1761. Note that in C and Objective C, unlike C++, the @code{inline} keyword
  1762. does not affect the linkage of the function.
  1763.  
  1764. @cindex automatic @code{inline} for C++ member fns
  1765. @cindex @code{inline} automatic for C++ member fns
  1766. @cindex member fns, automatically @code{inline}
  1767. @cindex C++ member fns, automatically @code{inline}
  1768. GNU CC automatically inlines member functions defined within the class
  1769. body of C++ programs even if they are not explicitly declared
  1770. @code{inline}.  (You can override this with @samp{-fno-default-inline};
  1771. @pxref{C++ Dialect Options,,Options Controlling C++ Dialect}.)
  1772.  
  1773. @cindex inline functions, omission of
  1774. When a function is both inline and @code{static}, if all calls to the
  1775. function are integrated into the caller, and the function's address is
  1776. never used, then the function's own assembler code is never referenced.
  1777. In this case, GNU CC does not actually output assembler code for the
  1778. function, unless you specify the option @samp{-fkeep-inline-functions}.
  1779. Some calls cannot be integrated for various reasons (in particular,
  1780. calls that precede the function's definition cannot be integrated, and
  1781. neither can recursive calls within the definition).  If there is a
  1782. nonintegrated call, then the function is compiled to assembler code as
  1783. usual.  The function must also be compiled as usual if the program
  1784. refers to its address, because that can't be inlined.
  1785.  
  1786. @cindex non-static inline function
  1787. When an inline function is not @code{static}, then the compiler must assume
  1788. that there may be calls from other source files; since a global symbol can
  1789. be defined only once in any program, the function must not be defined in
  1790. the other source files, so the calls therein cannot be integrated.
  1791. Therefore, a non-@code{static} inline function is always compiled on its
  1792. own in the usual fashion.
  1793.  
  1794. If you specify both @code{inline} and @code{extern} in the function
  1795. definition, then the definition is used only for inlining.  In no case
  1796. is the function compiled on its own, not even if you refer to its
  1797. address explicitly.  Such an address becomes an external reference, as
  1798. if you had only declared the function, and had not defined it.
  1799.  
  1800. This combination of @code{inline} and @code{extern} has almost the
  1801. effect of a macro.  The way to use it is to put a function definition in
  1802. a header file with these keywords, and put another copy of the
  1803. definition (lacking @code{inline} and @code{extern}) in a library file.
  1804. The definition in the header file will cause most calls to the function
  1805. to be inlined.  If any uses of the function remain, they will refer to
  1806. the single copy in the library.
  1807.  
  1808. GNU C does not inline any functions when not optimizing.  It is not
  1809. clear whether it is better to inline or not, in this case, but we found
  1810. that a correct implementation when not optimizing was difficult.  So we
  1811. did the easy thing, and turned it off.
  1812.  
  1813. @node Extended Asm
  1814. @section Assembler Instructions with C Expression Operands
  1815. @cindex extended @code{asm}
  1816. @cindex @code{asm} expressions
  1817. @cindex assembler instructions
  1818. @cindex registers
  1819.  
  1820. In an assembler instruction using @code{asm}, you can now specify the
  1821. operands of the instruction using C expressions.  This means no more
  1822. guessing which registers or memory locations will contain the data you want
  1823. to use.
  1824.  
  1825. You must specify an assembler instruction template much like what appears
  1826. in a machine description, plus an operand constraint string for each
  1827. operand.
  1828.  
  1829. For example, here is how to use the 68881's @code{fsinx} instruction:
  1830.  
  1831. @example
  1832. asm ("fsinx %1,%0" : "=f" (result) : "f" (angle));
  1833. @end example
  1834.  
  1835. @noindent
  1836. Here @code{angle} is the C expression for the input operand while
  1837. @code{result} is that of the output operand.  Each has @samp{"f"} as its
  1838. operand constraint, saying that a floating point register is required.  The
  1839. @samp{=} in @samp{=f} indicates that the operand is an output; all output
  1840. operands' constraints must use @samp{=}.  The constraints use the same
  1841. language used in the machine description (@pxref{Constraints}).
  1842.  
  1843. Each operand is described by an operand-constraint string followed by the C
  1844. expression in parentheses.  A colon separates the assembler template from
  1845. the first output operand, and another separates the last output operand
  1846. from the first input, if any.  Commas separate output operands and separate
  1847. inputs.  The total number of operands is limited to ten or to the maximum
  1848. number of operands in any instruction pattern in the machine description,
  1849. whichever is greater.
  1850.  
  1851. If there are no output operands, and there are input operands, then there
  1852. must be two consecutive colons surrounding the place where the output
  1853. operands would go.
  1854.  
  1855. Output operand expressions must be lvalues; the compiler can check this.
  1856. The input operands need not be lvalues.  The compiler cannot check whether
  1857. the operands have data types that are reasonable for the instruction being
  1858. executed.  It does not parse the assembler instruction template and does
  1859. not know what it means, or whether it is valid assembler input.  The
  1860. extended @code{asm} feature is most often used for machine instructions
  1861. that the compiler itself does not know exist.
  1862.  
  1863. The output operands must be write-only; GNU CC will assume that the values
  1864. in these operands before the instruction are dead and need not be
  1865. generated.  Extended asm does not support input-output or read-write
  1866. operands.  For this reason, the constraint character @samp{+}, which
  1867. indicates such an operand, may not be used.
  1868.  
  1869. When the assembler instruction has a read-write operand, or an operand
  1870. in which only some of the bits are to be changed, you must logically
  1871. split its function into two separate operands, one input operand and one
  1872. write-only output operand.  The connection between them is expressed by
  1873. constraints which say they need to be in the same location when the
  1874. instruction executes.  You can use the same C expression for both
  1875. operands, or different expressions.  For example, here we write the
  1876. (fictitious) @samp{combine} instruction with @code{bar} as its read-only
  1877. source operand and @code{foo} as its read-write destination:
  1878.  
  1879. @example
  1880. asm ("combine %2,%0" : "=r" (foo) : "0" (foo), "g" (bar));
  1881. @end example
  1882.  
  1883. @noindent
  1884. The constraint @samp{"0"} for operand 1 says that it must occupy the same
  1885. location as operand 0.  A digit in constraint is allowed only in an input
  1886. operand, and it must refer to an output operand.
  1887.  
  1888. Only a digit in the constraint can guarantee that one operand will be in
  1889. the same place as another.  The mere fact that @code{foo} is the value of
  1890. both operands is not enough to guarantee that they will be in the same
  1891. place in the generated assembler code.  The following would not work:
  1892.  
  1893. @example
  1894. asm ("combine %2,%0" : "=r" (foo) : "r" (foo), "g" (bar));
  1895. @end example
  1896.  
  1897. Various optimizations or reloading could cause operands 0 and 1 to be in
  1898. different registers; GNU CC knows no reason not to do so.  For example, the
  1899. compiler might find a copy of the value of @code{foo} in one register and
  1900. use it for operand 1, but generate the output operand 0 in a different
  1901. register (copying it afterward to @code{foo}'s own address).  Of course,
  1902. since the register for operand 1 is not even mentioned in the assembler
  1903. code, the result will not work, but GNU CC can't tell that.
  1904.  
  1905. Some instructions clobber specific hard registers.  To describe this, write
  1906. a third colon after the input operands, followed by the names of the
  1907. clobbered hard registers (given as strings).  Here is a realistic example
  1908. for the Vax:
  1909.  
  1910. @example
  1911. asm volatile ("movc3 %0,%1,%2"
  1912.               : /* no outputs */
  1913.               : "g" (from), "g" (to), "g" (count)
  1914.               : "r0", "r1", "r2", "r3", "r4", "r5");
  1915. @end example
  1916.  
  1917. If you refer to a particular hardware register from the assembler code,
  1918. then you will probably have to list the register after the third colon
  1919. to tell the compiler that the register's value is modified.  In many
  1920. assemblers, the register names begin with @samp{%}; to produce one
  1921. @samp{%} in the assembler code, you must write @samp{%%} in the input.
  1922.  
  1923. If your assembler instruction can alter the condition code register,
  1924. add @samp{cc} to the list of clobbered registers.  GNU CC on some
  1925. machines represents the condition codes as a specific hardware
  1926. register; @samp{cc} serves to name this register.  On other machines,
  1927. the condition code is handled differently, and specifying @samp{cc}
  1928. has no effect.  But it is valid no matter what the machine.
  1929.  
  1930. If your assembler instruction modifies memory in an unpredictable
  1931. fashion, add @samp{memory} to the list of clobbered registers.
  1932. This will cause GNU CC to not keep memory values cached in
  1933. registers across the assembler instruction.
  1934.  
  1935. You can put multiple assembler instructions together in a single @code{asm}
  1936. template, separated either with newlines (written as @samp{\n}) or with
  1937. semicolons if the assembler allows such semicolons.  The GNU assembler
  1938. allows semicolons and all Unix assemblers seem to do so.  The input
  1939. operands are guaranteed not to use any of the clobbered registers, and
  1940. neither will the output operands' addresses, so you can read and write the
  1941. clobbered registers as many times as you like.  Here is an example of
  1942. multiple instructions in a template; it assumes that the subroutine
  1943. @code{_foo} accepts arguments in registers 9 and 10:
  1944.  
  1945. @example
  1946. asm ("movl %0,r9;movl %1,r10;call _foo"
  1947.      : /* no outputs */
  1948.      : "g" (from), "g" (to)
  1949.      : "r9", "r10");
  1950. @end example
  1951.  
  1952. Unless an output operand has the @samp{&} constraint modifier, GNU CC may
  1953. allocate it in the same register as an unrelated input operand, on the
  1954. assumption that the inputs are consumed before the outputs are produced.
  1955. This assumption may be false if the assembler code actually consists of
  1956. more than one instruction.  In such a case, use @samp{&} for each output
  1957. operand that may not overlap an input.
  1958. @xref{Modifiers}.
  1959.  
  1960. If you want to test the condition code produced by an assembler instruction,
  1961. you must include a branch and a label in the @code{asm} construct, as follows:
  1962.  
  1963. @example
  1964. asm ("clr %0;frob %1;beq 0f;mov #1,%0;0:"
  1965.      : "g" (result)
  1966.      : "g" (input));
  1967. @end example
  1968.  
  1969. @noindent
  1970. This assumes your assembler supports local labels, as the GNU assembler
  1971. and most Unix assemblers do.
  1972.  
  1973. Speaking of labels, jumps from one @code{asm} to another are not
  1974. supported.  The compiler's optimizers do not know about these jumps,
  1975. and therefore they cannot take account of them when deciding how to
  1976. optimize.
  1977.  
  1978. @cindex macros containing @code{asm}
  1979. Usually the most convenient way to use these @code{asm} instructions is to
  1980. encapsulate them in macros that look like functions.  For example,
  1981.  
  1982. @example
  1983. #define sin(x)       \
  1984. (@{ double __value, __arg = (x);   \
  1985.    asm ("fsinx %1,%0": "=f" (__value): "f" (__arg));  \
  1986.    __value; @})
  1987. @end example
  1988.  
  1989. @noindent
  1990. Here the variable @code{__arg} is used to make sure that the instruction
  1991. operates on a proper @code{double} value, and to accept only those
  1992. arguments @code{x} which can convert automatically to a @code{double}.
  1993.  
  1994. Another way to make sure the instruction operates on the correct data type
  1995. is to use a cast in the @code{asm}.  This is different from using a
  1996. variable @code{__arg} in that it converts more different types.  For
  1997. example, if the desired type were @code{int}, casting the argument to
  1998. @code{int} would accept a pointer with no complaint, while assigning the
  1999. argument to an @code{int} variable named @code{__arg} would warn about
  2000. using a pointer unless the caller explicitly casts it.
  2001.  
  2002. If an @code{asm} has output operands, GNU CC assumes for optimization
  2003. purposes that the instruction has no side effects except to change the
  2004. output operands.  This does not mean that instructions with a side effect
  2005. cannot be used, but you must be careful, because the compiler may eliminate
  2006. them if the output operands aren't used, or move them out of loops, or
  2007. replace two with one if they constitute a common subexpression.  Also, if
  2008. your instruction does have a side effect on a variable that otherwise
  2009. appears not to change, the old value of the variable may be reused later if
  2010. it happens to be found in a register.
  2011.  
  2012. You can prevent an @code{asm} instruction from being deleted, moved
  2013. significantly, or combined, by writing the keyword @code{volatile} after
  2014. the @code{asm}.  For example:
  2015.  
  2016. @example
  2017. #define set_priority(x)  \
  2018. asm volatile ("set_priority %0": /* no outputs */ : "g" (x))
  2019. @end example
  2020.  
  2021. @noindent
  2022. An instruction without output operands will not be deleted or moved
  2023. significantly, regardless, unless it is unreachable.
  2024.  
  2025. Note that even a volatile @code{asm} instruction can be moved in ways
  2026. that appear insignificant to the compiler, such as across jump
  2027. instructions.  You can't expect a sequence of volatile @code{asm}
  2028. instructions to remain perfectly consecutive.  If you want consecutive
  2029. output, use a single @code{asm}.
  2030.  
  2031. It is a natural idea to look for a way to give access to the condition
  2032. code left by the assembler instruction.  However, when we attempted to
  2033. implement this, we found no way to make it work reliably.  The problem
  2034. is that output operands might need reloading, which would result in
  2035. additional following ``store'' instructions.  On most machines, these
  2036. instructions would alter the condition code before there was time to
  2037. test it.  This problem doesn't arise for ordinary ``test'' and
  2038. ``compare'' instructions because they don't have any output operands.
  2039.  
  2040. If you are writing a header file that should be includable in ANSI C
  2041. programs, write @code{__asm__} instead of @code{asm}.  @xref{Alternate
  2042. Keywords}.
  2043.  
  2044. @ifclear INTERNALS
  2045. @c Show the details on constraints if they do not appear elsewhere in
  2046. @c the manual
  2047. @include md.texi
  2048. @end ifclear
  2049.  
  2050. @node Asm Labels
  2051. @section Controlling Names Used in Assembler Code
  2052. @cindex assembler names for identifiers
  2053. @cindex names used in assembler code
  2054. @cindex identifiers, names in assembler code
  2055.  
  2056. You can specify the name to be used in the assembler code for a C
  2057. function or variable by writing the @code{asm} (or @code{__asm__})
  2058. keyword after the declarator as follows:
  2059.  
  2060. @example
  2061. int foo asm ("myfoo") = 2;
  2062. @end example
  2063.  
  2064. @noindent
  2065. This specifies that the name to be used for the variable @code{foo} in
  2066. the assembler code should be @samp{myfoo} rather than the usual
  2067. @samp{_foo}.
  2068.  
  2069. On systems where an underscore is normally prepended to the name of a C
  2070. function or variable, this feature allows you to define names for the
  2071. linker that do not start with an underscore.
  2072.  
  2073. You cannot use @code{asm} in this way in a function @emph{definition}; but
  2074. you can get the same effect by writing a declaration for the function
  2075. before its definition and putting @code{asm} there, like this:
  2076.  
  2077. @example
  2078. extern func () asm ("FUNC");
  2079.  
  2080. func (x, y)
  2081.      int x, y;
  2082. @dots{}
  2083. @end example
  2084.  
  2085. It is up to you to make sure that the assembler names you choose do not
  2086. conflict with any other assembler symbols.  Also, you must not use a
  2087. register name; that would produce completely invalid assembler code.  GNU
  2088. CC does not as yet have the ability to store static variables in registers.
  2089. Perhaps that will be added.
  2090.  
  2091. @node Explicit Reg Vars
  2092. @section Variables in Specified Registers
  2093. @cindex explicit register variables
  2094. @cindex variables in specified registers
  2095. @cindex specified registers
  2096. @cindex registers, global allocation
  2097.  
  2098. GNU C allows you to put a few global variables into specified hardware
  2099. registers.  You can also specify the register in which an ordinary
  2100. register variable should be allocated.
  2101.  
  2102. @itemize @bullet
  2103. @item
  2104. Global register variables reserve registers throughout the program.
  2105. This may be useful in programs such as programming language
  2106. interpreters which have a couple of global variables that are accessed
  2107. very often.
  2108.  
  2109. @item
  2110. Local register variables in specific registers do not reserve the
  2111. registers.  The compiler's data flow analysis is capable of determining
  2112. where the specified registers contain live values, and where they are
  2113. available for other uses.
  2114.  
  2115. These local variables are sometimes convenient for use with the extended
  2116. @code{asm} feature (@pxref{Extended Asm}), if you want to write one
  2117. output of the assembler instruction directly into a particular register.
  2118. (This will work provided the register you specify fits the constraints
  2119. specified for that operand in the @code{asm}.)
  2120. @end itemize
  2121.  
  2122. @menu
  2123. * Global Reg Vars::
  2124. * Local Reg Vars::
  2125. @end menu
  2126.  
  2127. @node Global Reg Vars
  2128. @subsection Defining Global Register Variables
  2129. @cindex global register variables
  2130. @cindex registers, global variables in
  2131.  
  2132. You can define a global register variable in GNU C like this:
  2133.  
  2134. @example
  2135. register int *foo asm ("a5");
  2136. @end example
  2137.  
  2138. @noindent
  2139. Here @code{a5} is the name of the register which should be used.  Choose a
  2140. register which is normally saved and restored by function calls on your
  2141. machine, so that library routines will not clobber it.
  2142.  
  2143. Naturally the register name is cpu-dependent, so you would need to
  2144. conditionalize your program according to cpu type.  The register
  2145. @code{a5} would be a good choice on a 68000 for a variable of pointer
  2146. type.  On machines with register windows, be sure to choose a ``global''
  2147. register that is not affected magically by the function call mechanism.
  2148.  
  2149. In addition, operating systems on one type of cpu may differ in how they
  2150. name the registers; then you would need additional conditionals.  For
  2151. example, some 68000 operating systems call this register @code{%a5}.
  2152.  
  2153. Eventually there may be a way of asking the compiler to choose a register
  2154. automatically, but first we need to figure out how it should choose and
  2155. how to enable you to guide the choice.  No solution is evident.
  2156.  
  2157. Defining a global register variable in a certain register reserves that
  2158. register entirely for this use, at least within the current compilation.
  2159. The register will not be allocated for any other purpose in the functions
  2160. in the current compilation.  The register will not be saved and restored by
  2161. these functions.  Stores into this register are never deleted even if they
  2162. would appear to be dead, but references may be deleted or moved or
  2163. simplified.
  2164.  
  2165. It is not safe to access the global register variables from signal
  2166. handlers, or from more than one thread of control, because the system
  2167. library routines may temporarily use the register for other things (unless
  2168. you recompile them specially for the task at hand).
  2169.  
  2170. @cindex @code{qsort}, and global register variables
  2171. It is not safe for one function that uses a global register variable to
  2172. call another such function @code{foo} by way of a third function
  2173. @code{lose} that was compiled without knowledge of this variable (i.e. in a
  2174. different source file in which the variable wasn't declared).  This is
  2175. because @code{lose} might save the register and put some other value there.
  2176. For example, you can't expect a global register variable to be available in
  2177. the comparison-function that you pass to @code{qsort}, since @code{qsort}
  2178. might have put something else in that register.  (If you are prepared to
  2179. recompile @code{qsort} with the same global register variable, you can
  2180. solve this problem.)
  2181.  
  2182. If you want to recompile @code{qsort} or other source files which do not
  2183. actually use your global register variable, so that they will not use that
  2184. register for any other purpose, then it suffices to specify the compiler
  2185. option @samp{-ffixed-@var{reg}}.  You need not actually add a global
  2186. register declaration to their source code.
  2187.  
  2188. A function which can alter the value of a global register variable cannot
  2189. safely be called from a function compiled without this variable, because it
  2190. could clobber the value the caller expects to find there on return.
  2191. Therefore, the function which is the entry point into the part of the
  2192. program that uses the global register variable must explicitly save and
  2193. restore the value which belongs to its caller.
  2194.  
  2195. @cindex register variable after @code{longjmp}
  2196. @cindex global register after @code{longjmp}
  2197. @cindex value after @code{longjmp}
  2198. @findex longjmp
  2199. @findex setjmp
  2200. On most machines, @code{longjmp} will restore to each global register
  2201. variable the value it had at the time of the @code{setjmp}.  On some
  2202. machines, however, @code{longjmp} will not change the value of global
  2203. register variables.  To be portable, the function that called @code{setjmp}
  2204. should make other arrangements to save the values of the global register
  2205. variables, and to restore them in a @code{longjmp}.  This way, the same
  2206. thing will happen regardless of what @code{longjmp} does.
  2207.  
  2208. All global register variable declarations must precede all function
  2209. definitions.  If such a declaration could appear after function
  2210. definitions, the declaration would be too late to prevent the register from
  2211. being used for other purposes in the preceding functions.
  2212.  
  2213. Global register variables may not have initial values, because an
  2214. executable file has no means to supply initial contents for a register.
  2215.  
  2216. On the Sparc, there are reports that g3 @dots{} g7 are suitable
  2217. registers, but certain library functions, such as @code{getwd}, as well
  2218. as the subroutines for division and remainder, modify g3 and g4.  g1 and
  2219. g2 are local temporaries.
  2220.  
  2221. On the 68000, a2 @dots{} a5 should be suitable, as should d2 @dots{} d7.
  2222. Of course, it will not do to use more than a few of those.
  2223.  
  2224. @node Local Reg Vars
  2225. @subsection Specifying Registers for Local Variables
  2226. @cindex local variables, specifying registers 
  2227. @cindex specifying registers for local variables
  2228. @cindex registers for local variables
  2229.  
  2230. You can define a local register variable with a specified register
  2231. like this:
  2232.  
  2233. @example
  2234. register int *foo asm ("a5");
  2235. @end example
  2236.  
  2237. @noindent
  2238. Here @code{a5} is the name of the register which should be used.  Note
  2239. that this is the same syntax used for defining global register
  2240. variables, but for a local variable it would appear within a function.
  2241.  
  2242. Naturally the register name is cpu-dependent, but this is not a
  2243. problem, since specific registers are most often useful with explicit
  2244. assembler instructions (@pxref{Extended Asm}).  Both of these things
  2245. generally require that you conditionalize your program according to
  2246. cpu type.
  2247.  
  2248. In addition, operating systems on one type of cpu may differ in how they
  2249. name the registers; then you would need additional conditionals.  For
  2250. example, some 68000 operating systems call this register @code{%a5}.
  2251.  
  2252. Eventually there may be a way of asking the compiler to choose a register
  2253. automatically, but first we need to figure out how it should choose and
  2254. how to enable you to guide the choice.  No solution is evident.
  2255.  
  2256. Defining such a register variable does not reserve the register; it
  2257. remains available for other uses in places where flow control determines
  2258. the variable's value is not live.  However, these registers are made
  2259. unavailable for use in the reload pass.  I would not be surprised if
  2260. excessive use of this feature leaves the compiler too few available
  2261. registers to compile certain functions.
  2262.  
  2263. @node Alternate Keywords
  2264. @section Alternate Keywords
  2265. @cindex alternate keywords
  2266. @cindex keywords, alternate
  2267.  
  2268. The option @samp{-traditional} disables certain keywords; @samp{-ansi}
  2269. disables certain others.  This causes trouble when you want to use GNU C
  2270. extensions, or ANSI C features, in a general-purpose header file that
  2271. should be usable by all programs, including ANSI C programs and traditional
  2272. ones.  The keywords @code{asm}, @code{typeof} and @code{inline} cannot be
  2273. used since they won't work in a program compiled with @samp{-ansi}, while
  2274. the keywords @code{const}, @code{volatile}, @code{signed}, @code{typeof}
  2275. and @code{inline} won't work in a program compiled with
  2276. @samp{-traditional}.@refill
  2277.  
  2278. The way to solve these problems is to put @samp{__} at the beginning and
  2279. end of each problematical keyword.  For example, use @code{__asm__}
  2280. instead of @code{asm}, @code{__const__} instead of @code{const}, and
  2281. @code{__inline__} instead of @code{inline}.
  2282.  
  2283. Other C compilers won't accept these alternative keywords; if you want to
  2284. compile with another compiler, you can define the alternate keywords as
  2285. macros to replace them with the customary keywords.  It looks like this:
  2286.  
  2287. @example
  2288. #ifndef __GNUC__
  2289. #define __asm__ asm
  2290. #endif
  2291. @end example
  2292.  
  2293. @samp{-pedantic} causes warnings for many GNU C extensions.  You can
  2294. prevent such warnings within one expression by writing
  2295. @code{__extension__} before the expression.  @code{__extension__} has no
  2296. effect aside from this.
  2297.  
  2298. @node Incomplete Enums
  2299. @section Incomplete @code{enum} Types
  2300.  
  2301. You can define an @code{enum} tag without specifying its possible values.
  2302. This results in an incomplete type, much like what you get if you write
  2303. @code{struct foo} without describing the elements.  A later declaration
  2304. which does specify the possible values completes the type.
  2305.  
  2306. You can't allocate variables or storage using the type while it is
  2307. incomplete.  However, you can work with pointers to that type.
  2308.  
  2309. This extension may not be very useful, but it makes the handling of
  2310. @code{enum} more consistent with the way @code{struct} and @code{union}
  2311. are handled.
  2312.  
  2313. This extension is not supported by GNU C++.
  2314.  
  2315. @node Function Names
  2316. @section Function Names as Strings
  2317.  
  2318. GNU CC predefines two string variables to be the name of the current function.
  2319. The variable @code{__FUNCTION__} is the name of the function as it appears
  2320. in the source.  The variable @code{__PRETTY_FUNCTION__} is the name of
  2321. the function pretty printed in a language specific fashion.
  2322.  
  2323. These names are always the same in a C function, but in a C++ function
  2324. they may be different.  For example, this program:
  2325.  
  2326. @smallexample
  2327. extern "C" @{
  2328. extern int printf (char *, ...);
  2329. @}
  2330.  
  2331. class a @{
  2332.  public:
  2333.   sub (int i)
  2334.     @{
  2335.       printf ("__FUNCTION__ = %s\n", __FUNCTION__);
  2336.       printf ("__PRETTY_FUNCTION__ = %s\n", __PRETTY_FUNCTION__);
  2337.     @}
  2338. @};
  2339.  
  2340. int
  2341. main (void)
  2342. @{
  2343.   a ax;
  2344.   ax.sub (0);
  2345.   return 0;
  2346. @}
  2347. @end smallexample
  2348.  
  2349. @noindent
  2350. gives this output:
  2351.  
  2352. @smallexample
  2353. __FUNCTION__ = sub
  2354. __PRETTY_FUNCTION__ = int  a::sub (int)
  2355. @end smallexample
  2356.  
  2357. @node C++ Extensions
  2358. @chapter Extensions to the C++ Language
  2359. @cindex extensions, C++ language
  2360. @cindex C++ language extensions
  2361.  
  2362. The GNU compiler provides these extensions to the C++ language (and you
  2363. can also use most of the C language extensions in your C++ programs).  If you
  2364. want to write code that checks whether these features are available, you can
  2365. test for the GNU compiler the same way as for C programs: check for a
  2366. predefined macro @code{__GNUC__}.  You can also use @code{__GNUG__} to
  2367. test specifically for GNU C++ (@pxref{Standard Predefined,,Standard
  2368. Predefined Macros,cpp.info,The C Preprocessor}).
  2369.  
  2370. @menu
  2371. * Naming Results::      Giving a name to C++ function return values.
  2372. * Min and Max::        C++ Minimum and maximum operators.
  2373. * Destructors and Goto:: Goto is safe to use in C++ even when destructors
  2374.                            are needed.
  2375. * C++ Interface::       You can use a single C++ header file for both
  2376.                          declarations and definitions.
  2377. * Template Instantiation:: Methods for ensuring that exactly one copy of
  2378.                          each needed template instantiation is emitted.
  2379. * C++ Signatures::    You can specify abstract types to get subtype
  2380.              polymorphism independent from inheritance.
  2381. @end menu
  2382.  
  2383. @node Naming Results
  2384. @section Named Return Values in C++
  2385.  
  2386. @cindex @code{return}, in C++ function header
  2387. @cindex return value, named, in C++
  2388. @cindex named return value in C++
  2389. @cindex C++ named return value
  2390. GNU C++ extends the function-definition syntax to allow you to specify a
  2391. name for the result of a function outside the body of the definition, in
  2392. C++ programs:
  2393.  
  2394. @example
  2395. @group
  2396. @var{type}
  2397. @var{functionname} (@var{args}) return @var{resultname};
  2398. @{ 
  2399.   @dots{}
  2400.   @var{body}
  2401.   @dots{}
  2402. @}
  2403. @end group
  2404. @end example
  2405.  
  2406. You can use this feature to avoid an extra constructor call when
  2407. a function result has a class type.  For example, consider a function
  2408. @code{m}, declared as @w{@samp{X v = m ();}}, whose result is of class
  2409. @code{X}:
  2410.  
  2411. @example
  2412. X
  2413. m ()
  2414. @{
  2415.   X b;
  2416.   b.a = 23;
  2417.   return b; 
  2418. @}
  2419. @end example
  2420.  
  2421. @cindex implicit argument: return value
  2422. Although @code{m} appears to have no arguments, in fact it has one implicit
  2423. argument: the address of the return value.  At invocation, the address
  2424. of enough space to hold @code{v} is sent in as the implicit argument.
  2425. Then @code{b} is constructed and its @code{a} field is set to the value
  2426. 23.  Finally, a copy constructor (a constructor of the form @samp{X(X&)})
  2427. is applied to @code{b}, with the (implicit) return value location as the
  2428. target, so that @code{v} is now bound to the return value.
  2429.  
  2430. But this is wasteful.  The local @code{b} is declared just to hold
  2431. something that will be copied right out.  While a compiler that
  2432. combined an ``elision'' algorithm with interprocedural data flow
  2433. analysis could conceivably eliminate all of this, it is much more
  2434. practical to allow you to assist the compiler in generating
  2435. efficient code by manipulating the return value explicitly,
  2436. thus avoiding the local variable and copy constructor altogether.
  2437.  
  2438. Using the extended GNU C++ function-definition syntax, you can avoid the
  2439. temporary allocation and copying by naming @code{r} as your return value
  2440. as the outset, and assigning to its @code{a} field directly:
  2441.  
  2442. @example
  2443. X
  2444. m () return r;
  2445. @{
  2446.   r.a = 23; 
  2447. @}
  2448. @end example
  2449.  
  2450. @noindent
  2451. The declaration of @code{r} is a standard, proper declaration, whose effects
  2452. are executed @strong{before} any of the body of @code{m}.
  2453.  
  2454. Functions of this type impose no additional restrictions; in particular,
  2455. you can execute @code{return} statements, or return implicitly by
  2456. reaching the end of the function body (``falling off the edge'').
  2457. Cases like 
  2458.  
  2459. @example
  2460. X
  2461. m () return r (23);
  2462. @{
  2463.   return; 
  2464. @}
  2465. @end example
  2466.  
  2467. @noindent
  2468. (or even @w{@samp{X m () return r (23); @{ @}}}) are unambiguous, since
  2469. the return value @code{r} has been initialized in either case.  The
  2470. following code may be hard to read, but also works predictably:
  2471.  
  2472. @example
  2473. X
  2474. m () return r;
  2475. @{
  2476.   X b;
  2477.   return b; 
  2478. @}
  2479. @end example
  2480.  
  2481. The return value slot denoted by @code{r} is initialized at the outset,
  2482. but the statement @samp{return b;} overrides this value.  The compiler
  2483. deals with this by destroying @code{r} (calling the destructor if there
  2484. is one, or doing nothing if there is not), and then reinitializing
  2485. @code{r} with @code{b}.
  2486.  
  2487. This extension is provided primarily to help people who use overloaded
  2488. operators, where there is a great need to control not just the
  2489. arguments, but the return values of functions.  For classes where the
  2490. copy constructor incurs a heavy performance penalty (especially in the
  2491. common case where there is a quick default constructor), this is a major
  2492. savings.  The disadvantage of this extension is that you do not control
  2493. when the default constructor for the return value is called: it is
  2494. always called at the beginning.
  2495.  
  2496. @node Min and Max
  2497. @section Minimum and Maximum Operators in C++
  2498.  
  2499. It is very convenient to have operators which return the ``minimum'' or the
  2500. ``maximum'' of two arguments.  In GNU C++ (but not in GNU C),
  2501.  
  2502. @table @code
  2503. @item @var{a} <? @var{b}
  2504. @findex <?
  2505. @cindex minimum operator
  2506. is the @dfn{minimum}, returning the smaller of the numeric values
  2507. @var{a} and @var{b};
  2508.  
  2509. @item @var{a} >? @var{b}
  2510. @findex >?
  2511. @cindex maximum operator
  2512. is the @dfn{maximum}, returning the larger of the numeric values @var{a}
  2513. and @var{b}.
  2514. @end table
  2515.  
  2516. These operations are not primitive in ordinary C++, since you can
  2517. use a macro to return the minimum of two things in C++, as in the
  2518. following example.
  2519.  
  2520. @example
  2521. #define MIN(X,Y) ((X) < (Y) ? : (X) : (Y))
  2522. @end example
  2523.  
  2524. @noindent
  2525. You might then use @w{@samp{int min = MIN (i, j);}} to set @var{min} to
  2526. the minimum value of variables @var{i} and @var{j}.
  2527.  
  2528. However, side effects in @code{X} or @code{Y} may cause unintended
  2529. behavior.  For example, @code{MIN (i++, j++)} will fail, incrementing
  2530. the smaller counter twice.  A GNU C extension allows you to write safe
  2531. macros that avoid this kind of problem (@pxref{Naming Types,,Naming an
  2532. Expression's Type}).  However, writing @code{MIN} and @code{MAX} as
  2533. macros also forces you to use function-call notation notation for a
  2534. fundamental arithmetic operation.  Using GNU C++ extensions, you can
  2535. write @w{@samp{int min = i <? j;}} instead.
  2536.  
  2537. Since @code{<?} and @code{>?} are built into the compiler, they properly
  2538. handle expressions with side-effects;  @w{@samp{int min = i++ <? j++;}}
  2539. works correctly.
  2540.  
  2541. @node Destructors and Goto
  2542. @section @code{goto} and Destructors in GNU C++
  2543.  
  2544. @cindex @code{goto} in C++
  2545. @cindex destructors vs @code{goto}
  2546. In C++ programs, you can safely use the @code{goto} statement.  When you
  2547. use it to exit a block which contains aggregates requiring destructors,
  2548. the destructors will run before the @code{goto} transfers control.  (In
  2549. ANSI C++, @code{goto} is restricted to targets within the current
  2550. block.)
  2551.  
  2552. @cindex constructors vs @code{goto}
  2553. The compiler still forbids using @code{goto} to @emph{enter} a scope
  2554. that requires constructors.
  2555.  
  2556. @node C++ Interface
  2557. @section Declarations and Definitions in One Header
  2558.  
  2559. @cindex interface and implementation headers, C++
  2560. @cindex C++ interface and implementation headers
  2561. C++ object definitions can be quite complex.  In principle, your source
  2562. code will need two kinds of things for each object that you use across
  2563. more than one source file.  First, you need an @dfn{interface}
  2564. specification, describing its structure with type declarations and
  2565. function prototypes.  Second, you need the @dfn{implementation} itself.
  2566. It can be tedious to maintain a separate interface description in a
  2567. header file, in parallel to the actual implementation.  It is also
  2568. dangerous, since separate interface and implementation definitions may
  2569. not remain parallel.
  2570.  
  2571. @cindex pragmas, interface and implementation
  2572. With GNU C++, you can use a single header file for both purposes.
  2573.  
  2574. @quotation
  2575. @emph{Warning:} The mechanism to specify this is in transition.  For the
  2576. nonce, you must use one of two @code{#pragma} commands; in a future
  2577. release of GNU C++, an alternative mechanism will make these
  2578. @code{#pragma} commands unnecessary.
  2579. @end quotation
  2580.  
  2581. The header file contains the full definitions, but is marked with
  2582. @samp{#pragma interface} in the source code.  This allows the compiler
  2583. to use the header file only as an interface specification when ordinary
  2584. source files incorporate it with @code{#include}.  In the single source
  2585. file where the full implementation belongs, you can use either a naming
  2586. convention or @samp{#pragma implementation} to indicate this alternate
  2587. use of the header file.
  2588.  
  2589. @table @code
  2590. @item #pragma interface
  2591. @itemx #pragma interface "@var{subdir}/@var{objects}.h"
  2592. @kindex #pragma interface
  2593. Use this directive in @emph{header files} that define object classes, to save
  2594. space in most of the object files that use those classes.  Normally,
  2595. local copies of certain information (backup copies of inline member
  2596. functions, debugging information, and the internal tables that implement
  2597. virtual functions) must be kept in each object file that includes class
  2598. definitions.  You can use this pragma to avoid such duplication.  When a
  2599. header file containing @samp{#pragma interface} is included in a
  2600. compilation, this auxiliary information will not be generated (unless
  2601. the main input source file itself uses @samp{#pragma implementation}).
  2602. Instead, the object files will contain references to be resolved at link
  2603. time.
  2604.  
  2605. The second form of this directive is useful for the case where you have
  2606. multiple headers with the same name in different directories.  If you
  2607. use this form, you must specify the same string to @samp{#pragma
  2608. implementation}.
  2609.  
  2610. @item #pragma implementation
  2611. @itemx #pragma implementation "@var{objects}.h"
  2612. @kindex #pragma implementation
  2613. Use this pragma in a @emph{main input file}, when you want full output from
  2614. included header files to be generated (and made globally visible).  The
  2615. included header file, in turn, should use @samp{#pragma interface}.
  2616. Backup copies of inline member functions, debugging information, and the
  2617. internal tables used to implement virtual functions are all generated in
  2618. implementation files.
  2619.  
  2620. @cindex implied @code{#pragma implementation}
  2621. @cindex @code{#pragma implementation}, implied
  2622. @cindex naming convention, implementation headers
  2623. If you use @samp{#pragma implementation} with no argument, it applies to
  2624. an include file with the same basename@footnote{A file's @dfn{basename}
  2625. was the name stripped of all leading path information and of trailing
  2626. suffixes, such as @samp{.h} or @samp{.C} or @samp{.cc}.} as your source
  2627. file.  For example, in @file{allclass.cc}, @samp{#pragma implementation}
  2628. by itself is equivalent to @samp{#pragma implementation "allclass.h"}.
  2629.  
  2630. In versions of GNU C++ prior to 2.6.0 @file{allclass.h} was treated as
  2631. an implementation file whenever you would include it from
  2632. @file{allclass.cc} even if you never specified @samp{#pragma
  2633. implementation}.  This was deemed to be more trouble than it was worth,
  2634. however, and disabled.
  2635.  
  2636. If you use an explicit @samp{#pragma implementation}, it must appear in
  2637. your source file @emph{before} you include the affected header files.
  2638.  
  2639. Use the string argument if you want a single implementation file to
  2640. include code from multiple header files.  (You must also use
  2641. @samp{#include} to include the header file; @samp{#pragma
  2642. implementation} only specifies how to use the file---it doesn't actually
  2643. include it.)
  2644.  
  2645. There is no way to split up the contents of a single header file into
  2646. multiple implementation files.
  2647. @end table
  2648.  
  2649. @cindex inlining and C++ pragmas
  2650. @cindex C++ pragmas, effect on inlining
  2651. @cindex pragmas in C++, effect on inlining
  2652. @samp{#pragma implementation} and @samp{#pragma interface} also have an
  2653. effect on function inlining.
  2654.  
  2655. If you define a class in a header file marked with @samp{#pragma
  2656. interface}, the effect on a function defined in that class is similar to
  2657. an explicit @code{extern} declaration---the compiler emits no code at
  2658. all to define an independent version of the function.  Its definition
  2659. is used only for inlining with its callers.
  2660.  
  2661. Conversely, when you include the same header file in a main source file
  2662. that declares it as @samp{#pragma implementation}, the compiler emits
  2663. code for the function itself; this defines a version of the function
  2664. that can be found via pointers (or by callers compiled without
  2665. inlining).  If all calls to the function can be inlined, you can avoid
  2666. emitting the function by compiling with @samp{-fno-implement-inlines}.
  2667. If any calls were not inlined, you will get linker errors.
  2668.  
  2669. @node Template Instantiation
  2670. @section Where's the Template?
  2671.  
  2672. @cindex template instantiation
  2673.  
  2674. C++ templates are the first language feature to require more
  2675. intelligence from the environment than one usually finds on a UNIX
  2676. system.  Somehow the compiler and linker have to make sure that each
  2677. template instance occurs exactly once in the executable if it is needed,
  2678. and not at all otherwise.  There are two basic approaches to this
  2679. problem, which I will refer to as the Borland model and the Cfront model.
  2680.  
  2681. @table @asis
  2682. @item Borland model
  2683. Borland C++ solved the template instantiation problem by adding the code
  2684. equivalent of common blocks to their linker; template instances
  2685. are emitted in each translation unit that uses them, and they are
  2686. collapsed together at run time.  The advantage of this model is that the
  2687. linker only has to consider the object files themselves; there is no
  2688. external complexity to worry about.  This disadvantage is that
  2689. compilation time is increased because the template code is being
  2690. compiled repeatedly.  Code written for this model tends to include
  2691. definitions of all member templates in the header file, since they must
  2692. be seen to be compiled.
  2693.  
  2694. @item Cfront model
  2695. The AT&T C++ translator, Cfront, solved the template instantiation
  2696. problem by creating the notion of a template repository, an
  2697. automatically maintained place where template instances are stored.  As
  2698. individual object files are built, notes are placed in the repository to
  2699. record where templates and potential type arguments were seen so that
  2700. the subsequent instantiation step knows where to find them.  At link
  2701. time, any needed instances are generated and linked in.  The advantages
  2702. of this model are more optimal compilation speed and the ability to use
  2703. the system linker; to implement the Borland model a compiler vendor also
  2704. needs to replace the linker.  The disadvantages are vastly increased
  2705. complexity, and thus potential for error; theoretically, this should be
  2706. just as transparent, but in practice it has been very difficult to build
  2707. multiple programs in one directory and one program in multiple
  2708. directories using Cfront.  Code written for this model tends to separate
  2709. definitions of non-inline member templates into a separate file, which
  2710. is magically found by the link preprocessor when a template needs to be
  2711. instantiated.
  2712. @end table
  2713.  
  2714. Currently, g++ implements neither automatic model.  The g++ team hopes
  2715. to have a repository working for 2.7.0.  In the mean time, you have
  2716. three options for dealing with template instantiations:
  2717.  
  2718. @enumerate
  2719. @item
  2720. Do nothing.  Pretend g++ does implement automatic instantiation
  2721. management.  Code written for the Borland model will work fine, but
  2722. each translation unit will contain instances of each of the templates it
  2723. uses.  In a large program, this can lead to an unacceptable amount of code
  2724. duplication.
  2725.  
  2726. @item
  2727. Add @samp{#pragma interface} to all files containing template
  2728. definitions.  For each of these files, add @samp{#pragma implementation
  2729. "@var{filename}"} to the top of some @samp{.C} file which
  2730. @samp{#include}s it.  Then compile everything with -fexternal-templates.
  2731. The templates will then only be expanded in the translation unit which
  2732. implements them (i.e. has a @samp{#pragma implementation} line for the
  2733. file where they live); all other files will use external references.  If
  2734. you're lucky, everything should work properly.  If you get undefined
  2735. symbol errors, you need to make sure that each template instance which
  2736. is used in the program is used in the file which implements that
  2737. template.  If you don't have any use for a particular instance in that
  2738. file, you can just instantiate it explicitly, using the syntax from the
  2739. latest C++ working paper:
  2740.  
  2741. @example
  2742. template class A<int>;
  2743. template ostream& operator << (ostream&, const A<int>&);
  2744. @end example
  2745.  
  2746. This strategy will work with code written for either model.  If you are
  2747. using code written for the Cfront model, the file containing a class
  2748. template and the file containing its member templates should be
  2749. implemented in the same translation unit.
  2750.  
  2751. A slight variation on this approach is to use the flag
  2752. -falt-external-templates instead; this flag causes template instances to
  2753. be emitted in the translation unit that implements the header where they
  2754. are first instantiated, rather than the one which implements the file
  2755. where the templates are defined.  This header must be the same in all
  2756. translation units, or things are likely to break.
  2757.  
  2758. @xref{C++ Interface,,Declarations and Definitions in One Header}, for
  2759. more discussion of these pragmas.
  2760.  
  2761. @item
  2762. Explicitly instantiate all the template instances you use, and compile
  2763. with -fno-implicit-templates.  This is probably your best bet; it may
  2764. require more knowledge of exactly which templates you are using, but
  2765. it's less mysterious than the previous approach, and it doesn't require
  2766. any @samp{#pragma}s or other g++-specific code.  You can scatter the
  2767. instantiations throughout your program, you can create one big file to
  2768. do all the instantiations, or you can create tiny files like
  2769.  
  2770. @example
  2771. #include "Foo.h"
  2772. #include "Foo.cc"
  2773.  
  2774. template class Foo<int>;
  2775. @end example
  2776.  
  2777. for each instance you need, and create a template instantiation library
  2778. from those.  I'm partial to the last, but your mileage may vary.  If you
  2779. are using Cfront-model code, you can probably get away with not using
  2780. -fno-implicit-templates when compiling files that don't @samp{#include}
  2781. the member template definitions.
  2782. @end enumerate
  2783.  
  2784. @node C++ Signatures
  2785. @section Type Abstraction using Signatures
  2786.  
  2787. @findex signature
  2788. @cindex type abstraction, C++
  2789. @cindex C++ type abstraction
  2790. @cindex subtype polymorphism, C++
  2791. @cindex C++ subtype polymorphism
  2792. @cindex signatures, C++
  2793. @cindex C++ signatures
  2794.  
  2795. In GNU C++, you can use the keyword @code{signature} to define a
  2796. completely abstract class interface as a datatype.  You can connect this
  2797. abstraction with actual classes using signature pointers.  If you want
  2798. to use signatures, run the GNU compiler with the
  2799. @samp{-fhandle-signatures} command-line option.  (With this option, the
  2800. compiler reserves a second keyword @code{sigof} as well, for a future
  2801. extension.)
  2802.  
  2803. Roughly, signatures are type abstractions or interfaces of classes.
  2804. Some other languages have similar facilities.  C++ signatures are
  2805. related to ML's signatures, Haskell's type classes, definition modules
  2806. in Modula-2, interface modules in Modula-3, abstract types in Emerald,
  2807. type modules in Trellis/Owl, categories in Scratchpad II, and types in
  2808. POOL-I.  For a more detailed discussion of signatures, see
  2809. @cite{Signatures: A C++ Extension for Type Abstraction and Subtype
  2810. Polymorphism} by @w{Gerald} Baumgartner and Vincent F. Russo (Tech report
  2811. CSD--TR--93--059, Dept. of Computer Sciences, Purdue University,
  2812. September 1993, to appear in @emph{Software Practice & Experience}).
  2813. You can get the tech report by anonymous FTP from
  2814. @code{ftp.cs.purdue.edu} in @file{pub/reports/TR93-059.PS.Z}.
  2815.  
  2816. Syntactically, a signature declaration is a collection of
  2817. member function declarations and nested type declarations.
  2818. For example, this signature declaration defines a new abstract type
  2819. @code{S} with member functions @samp{int foo ()} and @samp{int bar (int)}:
  2820.  
  2821. @example
  2822. signature S
  2823. @{
  2824.   int foo ();
  2825.   int bar (int);
  2826. @};
  2827. @end example
  2828.  
  2829. Since signature types do not include implementation definitions, you
  2830. cannot write an instance of a signature directly.  Instead, you can
  2831. define a pointer to any class that contains the required interfaces as a
  2832. @dfn{signature pointer}.  Such a class @dfn{implements} the signature
  2833. type.
  2834. @c Eventually signature references should work too.
  2835.  
  2836. To use a class as an implementation of @code{S}, you must ensure that
  2837. the class has public member functions @samp{int foo ()} and @samp{int
  2838. bar (int)}.  The class can have other member functions as well, public
  2839. or not; as long as it offers what's declared in the signature, it is
  2840. suitable as an implementation of that signature type.
  2841.  
  2842. For example, suppose that @code{C} is a class that meets the
  2843. requirements of signature @code{S} (@code{C} @dfn{conforms to}
  2844. @code{S}).  Then
  2845.  
  2846. @example
  2847. C obj;
  2848. S * p = &obj;
  2849. @end example
  2850.  
  2851. @noindent
  2852. defines a signature pointer @code{p} and initializes it to point to an
  2853. object of type @code{C}.  
  2854. The member function call @w{@samp{int i = p->foo ();}}
  2855. executes @samp{obj.foo ()}.
  2856.  
  2857. @cindex @code{signature} in C++, advantages
  2858. Abstract virtual classes provide somewhat similar facilities in standard
  2859. C++.  There are two main advantages to using signatures instead:
  2860.  
  2861. @enumerate
  2862. @item
  2863. Subtyping becomes independent from inheritance.  A class or signature
  2864. type @code{T} is a subtype of a signature type @code{S} independent of
  2865. any inheritance hierarchy as long as all the member functions declared
  2866. in @code{S} are also found in @code{T}.  So you can define a subtype
  2867. hierarchy that is completely independent from any inheritance
  2868. (implementation) hierarchy, instead of being forced to use types that
  2869. mirror the class inheritance hierarchy.
  2870.  
  2871. @item
  2872. Signatures allow you to work with existing class hierarchies as
  2873. implementations of a signature type.  If those class hierarchies are
  2874. only available in compiled form, you're out of luck with abstract virtual
  2875. classes, since an abstract virtual class cannot be retrofitted on top of
  2876. existing class hierarchies.  So you would be required to write interface
  2877. classes as subtypes of the abstract virtual class.
  2878. @end enumerate
  2879.  
  2880. @cindex default implementation, signature member function
  2881. @cindex signature member function default implemention
  2882. There is one more detail about signatures.  A signature declaration can
  2883. contain member function @emph{definitions} as well as member function
  2884. declarations.  A signature member function with a full definition is
  2885. called a @emph{default implementation}; classes need not contain that
  2886. particular interface in order to conform.  For example, a
  2887. class @code{C} can conform to the signature
  2888.  
  2889. @example
  2890. signature T
  2891. @{
  2892.   int f (int);
  2893.   int f0 () @{ return f (0); @};
  2894. @};
  2895. @end example
  2896.  
  2897. @noindent
  2898. whether or not @code{C} implements the member function @samp{int f0 ()}.
  2899. If you define @code{C::f0}, that definition takes precedence;
  2900. otherwise, the default implementation @code{S::f0} applies.
  2901.  
  2902. @ignore
  2903. There will be more support for signatures in the future.
  2904. Add to this doc as the implementation grows.
  2905. In particular, the following features are planned but not yet
  2906. implemented:
  2907. @itemize @bullet
  2908. @item signature references,
  2909. @item signature inheritance,
  2910. @item the @code{sigof} construct for extracting the signature information
  2911.       of a class,
  2912. @item views for renaming member functions when matching a class type
  2913.       with a signature type,
  2914. @item specifying exceptions with signature member functions, and
  2915. @item signature templates.
  2916. @end itemize
  2917. This list is roughly in the order in which we intend to implement
  2918. them.  Watch this space for updates.
  2919. @end ignore
  2920.